13.07.2015 Views

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 448.3. connect()Connect a socket <strong>to</strong> a serverPro<strong>to</strong>types#include #include int connect(int sockfd, const struct sockaddr *serv_addr,socklen_t addrlen);DescriptionOnce you’ve built a socket descrip<strong>to</strong>r with the socket() call, you can connect() that socket<strong>to</strong> a remote server using the well-named connect() system call. All you need <strong>to</strong> do is pass it thesocket descrip<strong>to</strong>r and the address of the server you’re interested in getting <strong>to</strong> know better. (Oh, andthe length of the address, which is commonly passed <strong>to</strong> functions like this.)If you haven’t yet called bind() on the socket descrip<strong>to</strong>r, it is au<strong>to</strong>matically bound <strong>to</strong> yourIP address and a random local port. This is usually just fine with you, since you really don’t carewhat your local port is; you only care what the remote port is so you can put it in the serv_addrparameter. You can call bind() if you really want your client socket <strong>to</strong> be on a specific IP addressand port, but this is pretty rare.Once the socket is connect()ed, you’re free <strong>to</strong> send() and recv() data on it <strong>to</strong> your heart’scontent.Special note: if you connect() a SOCK_DGRAM UDP socket <strong>to</strong> a remote host, you can usesend() and recv() as well as send<strong>to</strong>() and recvfrom(). If you want.Return ValueReturns zero on success, or -1 on error (and errno will be set accordingly.)Exampleint s;struct sockaddr_in serv_addr;// pretend the server is at 63.161.169.137 listening on port 80:myaddr.sin_family = AF_INET;myaddr.sin_port = h<strong>to</strong>ns(80);inet_a<strong>to</strong>n("63.161.169.137", &myaddr.sin_addr.s_addr);s = socket(PF_INET, SOCK_STREAM, 0);connect(s, (struct sockaddr*)myaddr, sizeof(myaddr));// now we’re ready <strong>to</strong> send() and recv()See Alsosocket(), bind()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!