bind函数详解

看看man手册:

BIND(2)                    Linux Programmer's Manual                   BIND(2)

NAME
       bind - bind a name to a socket

SYNOPSIS
       #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>

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

DESCRIPTION
       When  a  socket  is  created  with socket(2), it exists in a name space
       (address family) but has no address assigned to it.  bind() assigns the
       address  specified  by  addr  to  the  socket  referred  to by the file
       descriptor sockfd.  addrlen  specifies  the  size,  in  bytes,  of  the
       address structure pointed to by addr.  Traditionally, this operation is
       called “assigning a name to a socket”.

       It is normally necessary to assign a local address using bind()  before
       a SOCK_STREAM socket may receive connections (see accept(2)).

       The  rules used in name binding vary between address families.  Consult
       the manual entries in Section 7 for detailed information.  For  AF_INET
       see  ip(7),  for  AF_INET6  see  ipv6(7),  for AF_UNIX see unix(7), for
       AF_APPLETALK see ddp(7), for AF_PACKET see packet(7),  for  AF_X25  see
       x25(7) and for AF_NETLINK see netlink(7).

       The  actual  structure  passed for the addr argument will depend on the
       address family.  The sockaddr structure is defined as something like:

           struct sockaddr {
               sa_family_t sa_family;
               char        sa_data[14];
           }

       The only purpose of this structure is to  cast  the  structure  pointer
       passed in addr in order to avoid compiler warnings.  See EXAMPLE below.

RETURN VALUE
       On  success,  zero is returned.  On error, -1 is returned, and errno is
       set appropriately.

ERRORS
       EACCES The address is protected, and the user is not the superuser.

       EADDRINUSE
              The given address is already in use.

       EADDRINUSE
              (Internet domain sockets) The port number was specified as  zero
              in the socket address structure, but, upon attempting to bind to
              an ephemeral port, it was determined that all  port  numbers  in
              the  ephemeral port range are currently in use.  See the discus‐
              sion of /proc/sys/net/ipv4/ip_local_port_range ip(7).

       EBADF  sockfd is not a valid descriptor.

       EINVAL The socket is already bound to an address.

       EINVAL addrlen is wrong, or addr  is  not  a  valid  address  for  this
              socket's domain.

       ENOTSOCK
              The file descriptor sockfd does not refer to a socket.

       The following errors are specific to UNIX domain (AF_UNIX) sockets:

       EACCES Search  permission  is denied on a component of the path prefix.
              (See also path_resolution(7).)

       EADDRNOTAVAIL
              A nonexistent interface was requested or the  requested  address
              was not local.

       EFAULT addr points outside the user's accessible address space.

       ELOOP  Too many symbolic links were encountered in resolving addr.

       ENAMETOOLONG
              addr is too long.

       ENOENT The file does not exist.

       ENOMEM Insufficient kernel memory was available.

       ENOTDIR
              A component of the path prefix is not a directory.

       EROFS  The socket inode would reside on a read-only filesystem.

CONFORMING TO
       POSIX.1-2001,  POSIX.1-2008,  SVr4,  4.4BSD  (bind()  first appeared in
       4.2BSD).

NOTES
       POSIX.1 does not require  the  inclusion  of  <sys/types.h>,  and  this
       header  file  is not required on Linux.  However, some historical (BSD)
       implementations required this header file,  and  portable  applications
       are probably wise to include it.

       The third argument of bind() is in reality an int (and this is what 4.x
       BSD and libc4 and libc5 have).  Some POSIX confusion  resulted  in  the
       present socklen_t, also used by glibc.  See also accept(2).

BUGS
       The transparent proxy options are not described.

EXAMPLE
       An  example  of  the  use of bind() with Internet domain sockets can be
       found in getaddrinfo(3).

       The following example shows how to bind a stream  socket  in  the  UNIX
       (AF_UNIX) domain, and accept connections:

       #include <sys/socket.h>
       #include <sys/un.h>
       #include <stdlib.h>
       #include <stdio.h>
       #include <string.h>

       #define MY_SOCK_PATH "/somepath"
       #define LISTEN_BACKLOG 50

       #define handle_error(msg) \
           do { perror(msg); exit(EXIT_FAILURE); } while (0)

       int
       main(int argc, char *argv[])
       {
           int sfd, cfd;
           struct sockaddr_un my_addr, peer_addr;
           socklen_t peer_addr_size;

           sfd = socket(AF_UNIX, SOCK_STREAM, 0);
           if (sfd == -1)
               handle_error("socket");

           memset(&my_addr, 0, sizeof(struct sockaddr_un));
                               /* Clear structure */
           my_addr.sun_family = AF_UNIX;
           strncpy(my_addr.sun_path, MY_SOCK_PATH,
                   sizeof(my_addr.sun_path) - 1);

           if (bind(sfd, (struct sockaddr *) &my_addr,
                   sizeof(struct sockaddr_un)) == -1)
               handle_error("bind");

           if (listen(sfd, LISTEN_BACKLOG) == -1)
               handle_error("listen");

           /* Now we can accept incoming connections one
              at a time using accept(2) */

           peer_addr_size = sizeof(struct sockaddr_un);
           cfd = accept(sfd, (struct sockaddr *) &peer_addr,
                        &peer_addr_size);
           if (cfd == -1)
               handle_error("accept");

           /* Code to deal with incoming connection(s)... */

           /* When no longer required, the socket pathname, MY_SOCK_PATH
              should be deleted using unlink(2) or remove(3) */
       }

SEE ALSO
       accept(2),  connect(2),  getsockname(2),  listen(2),  socket(2), getad‐
       drinfo(3),   getifaddrs(3),   ip(7),    ipv6(7),    path_resolution(7),
       socket(7), unix(7)

COLOPHON
       This  page  is  part of release 4.04 of the Linux man-pages project.  A
       description of the project, information about reporting bugs,  and  the
       latest     version     of     this    page,    can    be    found    at
       http://www.kernel.org/doc/man-pages/.

Linux                             2015-12-28                           BIND(2)

函数原型:

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>

 int bind(int sockfd, const struct sockaddr *addr,
                socklen_t addrlen);
           成功返回0,出错返回-1

man中给的例程:

#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MY_SOCK_PATH "/somepath"
#define LISTEN_BACKLOG 50

#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)

 int
   main(int argc, char *argv[])
    {
           int sfd, cfd;
           struct sockaddr_un my_addr, peer_addr;
           socklen_t peer_addr_size;

           sfd = socket(AF_UNIX, SOCK_STREAM, 0);
           if (sfd == -1)
               handle_error("socket");

           memset(&my_addr, 0, sizeof(struct sockaddr_un));
                               /* Clear structure */
           my_addr.sun_family = AF_UNIX;
           strncpy(my_addr.sun_path, MY_SOCK_PATH,
                   sizeof(my_addr.sun_path) - 1);

           if (bind(sfd, (struct sockaddr *) &my_addr,
                   sizeof(struct sockaddr_un)) == -1)
               handle_error("bind");

           if (listen(sfd, LISTEN_BACKLOG) == -1)
               handle_error("listen");

           /* Now we can accept incoming connections one
              at a time using accept(2) */

           peer_addr_size = sizeof(struct sockaddr_un);
           cfd = accept(sfd, (struct sockaddr *) &peer_addr,
                        &peer_addr_size);
           if (cfd == -1)
               handle_error("accept");

           /* Code to deal with incoming connection(s)... */

   /* When no longer required, the socket pathname, MY_SOCK_PATH
              should be deleted using unlink(2) or remove(3) */
    }

服务器端和客户端程序的显著区别在于客户端程序不需要调用bind函数,bind函数的作用是将套接字绑定一个IP地址和端口号,因为这两个元素可以在网络环境中唯一地址表示一个进程。如果套接字没有使用bind函数绑定地址和端口,那么调用listen函数和connect函数的时候内核会自动为套接字绑定。由此可知,如果没有使用bind函数,调用listen函数和connect函数的时候内核会自动为套接字绑定。看起来好像bind函数是多余的,但事实并不是这样。

我们先来看看listen函数和connect是怎么绑定套接字的,connect函数绑定套接字的时候使用的是一个设置好的地址结构(sockaddr_in)作为参数,结构中指定了服务器的地址和需要通信的端口号。但是listen函数没有这个参数,多以listen函数不能够使用设置好的地址结构,只能由系统设置IP地址和端口号。也就是说在服务器端,如果不使用bind函数的话,创建套接字时使用的是当前系统中空闲端口的套接字。

这样的话,服务器端的程序不关心客户端的IP地址,也就说是对应的端口号是内核临时指派的一个端口,是随机的,每次执行服务器程序的时候,使用的都是不同的端口。但是在客户端是需要指定通信的服务器的端口的,如果不使用bind函数,每次的端口是随机的话,那么每次重启服务程序之后都要对客户端的程序进行调整,这样做不仅不合理,而且工作量很大,因此在服务器端bind函数作用非常重要。
使用bind函数的历程:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAX_LINE 100

int main(void)
{
       struct sockaddr_in sin;
       struct sockaddr_in cin;
       int l_fd;
       int c_fd;
       socklen_t len;
       char buf[MAX_LINE];
       char addr_p[INET_ADDRSTRLEN];
       int port = 8000;
       int n;
       bzero(&sin, sizeof(sin));
       sin.sin_family = AF_INET;
       sin.sin_addr.s_addr = INADDR_ANY;
       sin.sin_port = htons(port);
       /*创立套接字,使用TCP协议*/
       if((l_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
       {
              perror("fail to creat socket");
              exit(1);
       }
       /*将地址和套节字绑定*/
       if(bind(l_fd, (struct sockaddr *) &sin, sizeof(sin)) == -1)
       {
              perror("fail to bind");
              exit(1);
       }
       /*开始监听连接请求*/
       if(listen(l_fd, 10) == -1)
       {
              perror("fail to listren");
              exit(1);
       }
       printf("waiting...\n");
       while(1)
       {
              /*接受连接请求,从此函数中返回后就可以开始通信了*/
              if((c_fd = accept(l_fd, (struct sockaddr *) &cin, &len)) == -1)
              {
                     perror("fail to accept");
                     exit(1);
              }
              /*调用recv函数读取客户端传来的信息,不设置任何特殊的标志*/
              n = recv(c_fd, buf, MAX_LINE, 0);
             if(n = -1)
              {
                     perror("fail to receive");
                     exit(1);
              }
              else if(n == 0)
              {
                     printf("the connect has been closed\n ");
                     close(c_fd);
                     continue;
              }
              /*将客户端地址转换为字符串*/
              inet_ntop(AF_INET, &cin.sin_addr, addr_p, sizeof(addr_p));
              printf("client IP is %s, port is %s \n", addr_p, ntohs(cin.sin_port));
              printf("connect is : %s\n", buf);
              n = strlen(buf);
              sprintf(buf, "%d", n);
              /*使用send函数将转换后的字符串发送给客户端,不设置任何特殊的标志*/
              n = send(c_fd, buf, strlen(buf) + 1, 0);
              if(n == -1)
              {
                     perror("fail to send");
                     exit(1);
              }
              if(cloes(c_fd) == -1)
              {
                     perror("fail to close");
                     exit(1);
              }
       }
       return 0;
}

猜你喜欢

转载自blog.csdn.net/andrewgithub/article/details/81638970
今日推荐