Socket connect () vs bind ()

Both connect() and bind() system calls "bind" the socket file descriptor to the address (usually a combination of ip / port). Their prototypes are similar to: -

 int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen); 

and

 int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); 

What is the difference between two calls? When should connect() be used and when is bind() ?

In particular, in some examples of client server codes, the client has detected that the client is using connect() , and the server is using the bind() call. The reason was not fully understood by me.

+100
c sockets network-programming
Nov 19 '14 at 10:49
source share
6 answers

To better understand, let's find out exactly where they connect and connect,

In addition to positioning the two calls, as Suraw explained,

bind () binds the socket to its local address [therefore, the server part binds, so clients can use this address to connect to the server.] connect () is used to connect to the remote address [of the server], so connect [read as: connect to server].

We cannot use them interchangeably (even if we have a client / server on the same machine) due to certain roles and the corresponding implementation.

Next, I recommend matching these TCP / IP calls with a handshake.

enter image description here

So, whoever sends SYN here, it will be connected (). While bind () is used to determine the endpoint of a connection.

Hope this helps !!

+190
Nov 19 '14 at 13:10
source share

One liner: bind() for its own address, connect() for a remote address.

Quote from the bind() man page

bind () assigns the address indicated by addr to the socket specified by the sockfd file descriptor. addrlen determines the size in bytes of the address structure pointed to by addr. Traditionally, this operation is called "naming a socket".

and, from the same for connect()

The connect () system call connects the socket referenced by the sockfd file descriptor to the address specified by addr.

To clarify,

  • bind() associates the socket with its local address [why server side bind s so that clients can use this address to connect to the server.]
  • connect() used to connect to the remote [server] address, why the client side connect [read as: connect to the server].
+40
Nov 19 '14 at 10:52
source share

bind tells the running process to request a port. those. it must bind to port 80 and listen for incoming requests. with binding, your process becomes a server. when you use the connection, you tell your process to connect to the port that is ALREADY used. Your process becomes a customer. the difference is important: bind wants a port that is not in use (so that it can claim to become a server), and connect wants to use a port that is already in use (so that it can connect to it and talk to the server)

+8
Nov 19 '14 at 13:28
source share

From Wikipedia http://en.wikipedia.org/wiki/Berkeley_sockets#bind.28.29

connection ():

The connect () system call connects the socket identified by the file descriptor to the remote host specified by the host address in the argument list.

Some types of sockets are connectionless connections, most often these are user datagram protocol sockets. For these sockets, connect takes on special significance: the default target for sending and receiving data is set to the specified address, which allows you to use functions such as send () and recv () for sockets without establishing a connection.

connect () returns an integer representing the error code: 0 represents success, while -1 represents error.

Bind ():

bind () assigns a socket to an address. When a socket is created using socket (), only the protocol family is assigned to it, but no address is assigned. This communication with the address must be done using the bind () system call before the socket can accept connections with other hosts. bind () takes three arguments:

sockfd, a handle representing the socket to bind to. my_addr, a pointer to a sockaddr structure representing the address to bind. addrlen, a socklen_t field that defines the size of the sockaddr structure. Bind () returns 0 on success and -1 on failure.

Examples: 1.) Using Connect

 #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main(){ int clientSocket; char buffer[1024]; struct sockaddr_in serverAddr; socklen_t addr_size; /*---- Create the socket. The three arguments are: ----*/ /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */ clientSocket = socket(PF_INET, SOCK_STREAM, 0); /*---- Configure settings of the server address struct ----*/ /* Address family = Internet */ serverAddr.sin_family = AF_INET; /* Set port number, using htons function to use proper byte order */ serverAddr.sin_port = htons(7891); /* Set the IP address to desired host to connect to */ serverAddr.sin_addr.s_addr = inet_addr("192.168.1.17"); /* Set all bits of the padding field to 0 */ memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero); /*---- Connect the socket to the server using the address struct ----*/ addr_size = sizeof serverAddr; connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size); /*---- Read the message from the server into the buffer ----*/ recv(clientSocket, buffer, 1024, 0); /*---- Print the received message ----*/ printf("Data received: %s",buffer); return 0; } 

2.) An example of a binding:

 int main() { struct sockaddr_in source, destination = {}; //two sockets declared as previously int sock = 0; int datalen = 0; int pkt = 0; uint8_t *send_buffer, *recv_buffer; struct sockaddr_storage fromAddr; // same as the previous entity struct sockaddr_storage serverStorage; unsigned int addrlen; //in the previous example socklen_t addr_size; struct timeval tv; tv.tv_sec = 3; /* 3 Seconds Time-out */ tv.tv_usec = 0; /* creating the socket */ if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) printf("Failed to create socket\n"); /*set the socket options*/ setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)); /*Inititalize source to zero*/ memset(&source, 0, sizeof(source)); //source is an instance of sockaddr_in. Initialization to zero /*Inititalize destinaton to zero*/ memset(&destination, 0, sizeof(destination)); /*---- Configure settings of the source address struct, WHERE THE PACKET IS COMING FROM ----*/ /* Address family = Internet */ source.sin_family = AF_INET; /* Set IP address to localhost */ source.sin_addr.s_addr = INADDR_ANY; //INADDR_ANY = 0.0.0.0 /* Set port number, using htons function to use proper byte order */ source.sin_port = htons(7005); /* Set all bits of the padding field to 0 */ memset(source.sin_zero, '\0', sizeof source.sin_zero); //optional /*bind socket to the source WHERE THE PACKET IS COMING FROM*/ if (bind(sock, (struct sockaddr *) &source, sizeof(source)) < 0) printf("Failed to bind socket"); /* setting the destination, ie our OWN IP ADDRESS AND PORT */ destination.sin_family = AF_INET; destination.sin_addr.s_addr = inet_addr("127.0.0.1"); destination.sin_port = htons(7005); //Creating a Buffer; send_buffer=(uint8_t *) malloc(350); recv_buffer=(uint8_t *) malloc(250); addrlen=sizeof(fromAddr); memset((void *) recv_buffer, 0, 250); memset((void *) send_buffer, 0, 350); sendto(sock, send_buffer, 20, 0,(struct sockaddr *) &destination, sizeof(destination)); pkt=recvfrom(sock, recv_buffer, 98,0,(struct sockaddr *)&destination, &addrlen); if(pkt > 0) printf("%u bytes received\n", pkt); } 

I hope this clarifies the difference

Please note that the type of socket you declare will depend on what you require, it is very important

+7
Nov 19 '14 at 11:37
source share

I think this will help your understanding if you think of connect() and listen() as analogues, not connect() and bind() . The reason for this is that you can call or omit bind() before any of them, although it is rarely recommended to call it before connect() or not call it before listen() .

If this helps to think from the point of view of servers and clients, it is listen() which is the hallmark of the first, and connect() second. bind() can be found - or not found - either on.

If we assume that our server and client are on different machines, it becomes easier to understand the various functions.

bind() acts locally, that is, it binds the end of the connection on the machine on which it is called to the requested address and assigns you the requested port. This happens regardless of whether this machine is a client or server. connect() initiates a connection to the server, that is, it connects to the requested address and port on the server from the client. This server almost certainly called bind() before listen() so that you could know at what address and port to connect to it using connect() .

If you do not call bind() , the port and address will be implicitly assigned and bound to the local machine for you when you call connect() (client) or listen() (server). However, this is a side effect of both, not their goal. The port so designated is ephemeral.

The important point here is that the client does not have to be connected, because the clients connect to the servers, and therefore the server will know the address and port of the client, even if you use a temporary port, rather than being attached to something specific. On the other hand, although the server can call listen() without calling bind() , in this scenario it will need to detect the ephemeral port assigned to it and notify any client who wants to connect to it.

I assume that, as you mentioned connect() you are interested in TCP, but it also carries over to UDP, where without calling bind() before the first sendto() (UDP does not use a connection), it also calls the port and address to be implicit assigned and bound. One function that you cannot call without binding is recvfrom() , which will return an error because without the assigned port and associated address there is nothing to receive (or too much, depending on how you interpret the lack of binding).

+5
Jan 17 '18 at 14:50
source share

Too long; Do not read. The difference is which source (local) or destination address / port. In short, bind() sets the source, and connect() sets the destination. Regardless of TCP or UDP.

bind()

bind() sets the local (source) address of the socket. This is the address where packets are received. Packets sent by the socket contain this as the source address, so the other host will know where to send their packets back.

If receiving is not required, the socket source address is useless. Protocols such as TCP require that reception be turned on for proper sending, since the destination host sends back an acknowledgment when one or more packets arrived (i.e., acknowledgment).

connect()

  • TCP has a โ€œconnectedโ€ state. connect() runs the TCP code to try to establish a connection with the other side.
  • UDP does not have a โ€œconnectedโ€ state. connect() sets the default address where packets are sent if the address is not specified. If connect() not used, sendto() use sendto() or sendmsg() containing the destination address.

When the connect() or send function is called and the address is not bound, Linux automatically associates the socket with a random port. For technical details, look at inet_autobind() in the source code of the Linux kernel.

Side notes

  • listen() for TCP only.
  • In the AF_INET family, the socket source or destination address ( struct sockaddr_in ) consists of an IP address (see IP Header ) and a TCP or UDP port (see TCP and UDP Header).
+1
Oct 02 '18 at 20:56
source share



All Articles