如何在C中获取socket的地址ip

时间:2015-11-11 14:36:58

标签: c linux sockets

我想通过套接字获取IP地址。我的代码:

      .
      .
      .
int socket_server = socket(AF_INET, SOCK_STREAM, 0);

adresse_serveur.sin_family      = AF_INET; // le domain
adresse_serveur.sin_addr.s_addr = htonl(INADDR_ANY);
adresse_serveur.sin_port        = htons(2018);

int taille_de_structure = sizeof(adresse_serveur);
bind(socket_server, (struct sockaddr*)&adresse_serveur, taille_de_structure);
      .
      .
      .

1 个答案:

答案 0 :(得分:1)

套接字已绑定到INADDR_ANY端口2018。它没有比这更具体的地址。 INADDR_ANY表示套接字将在其任何接口上accept连接。它没有连接,因此它没有远程地址。

由于套接字显然是要在服务器中使用,因此您需要调用listen然后accept来获取一个新的连接套接字(假设它实际上是connects )。连接的套接字将具有绑定到其本地和远程端的更具体的地址。您可以通过拨打getsockname和远程地址来拨打getpeername来获取本地地址。

以下是TCP服务器的外观(所有错误检查都留给读者阅读):

struct sockaddr_in sin;

/* create socket */
int sd = socket(AF_INET, SOCK_STREAM, 0);

/* bind socket to port 2018, any interface */
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(2018);
bind(sd, (struct sockaddr*)&sin, sizeof(sin));

/* start listening for connections */
listen(sd, 5);

/* accept connections forever */
while (1) {
    struct sockaddr_in remote_sin;
    socklen_t remote_sinlen = sizeof(remote_sin);
    struct sockaddr_in local_sin;
    socklen_t local_sinlen = sizeof(local_sin);

    /* wait for a connection */
    int nsd = accept(sd, (struct sockaddr*)&remote_sin, &remote_sinlen);

    /* get the local address of the connected socket */
    getsockname(nsd, (struct sockaddr*)&local_sin, &local_sinlen);

    /* local address is in local_sin.  local_sinlen should still be sizeof(local_sin).
     * remote address is in remote_sin.  remote_sinlen should still be sizeof(remote_sin).
     */

    /* service connection, or fork a child to do it, or whatever... */

    /* close the connection */
    close(nsd);
}