bind |
Prototype: |
#include <sys/socket.h>
#include <resolv.h>
int bind(int sockfd, struct sockaddr* addr,
int addrlen);
|
General Description: |
Defines a port or name to a socket. If you want a consistent port for an incoming connection, you have to bind your socket to a port. In most instances, the kernel automatically calls bind() for the socket if you do not call it explicitly. The kernel-generated port assignment may be different from execution to execution. |
Return Value: |
Zero (0) if everything goes well. If an error occurs, you can find the cause in errno. |
Parameters |
sockfd |
The socket descriptor to bind. |
addr |
The port assignment or name. |
addrlen |
The length of addr, because addr may be different sizes. |
Possible Errors |
EBADF |
sockfd is not a valid descriptor. |
EINVAL |
The socket is already bound to an address. This may change in the future: see .../linux/unix/socket.c for details. |
EACCES |
The address is protected, and the user is not the super-user. |
ENOTSOCK |
Argument is a descriptor for a file, not a socket. |
Examples |
int sockfd;
struct sockaddr_in addr;
sockfd = socket(PF_INET, SOCKET_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(9999); /* or whatever port you want */
/* to bind any network interface */
addr.sin_addr.s_addr = INADDR_ANY;
/* -or- to bind a specific interface, use this: */
/* inet_aton("128.1.1.1", &addr.sin_addr); */
if ( bind(sockfd, &addr, sizeof(addr)) != 0 )
perror("bind");
|