修改服务器,使其只侦听环回接口

时间:2014-10-22 04:09:06

标签: c networking netstat

我试图运行客户端服务器连接。这是我的代码:

server.c

#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <string.h>

#define MAX_BUFFER 128
#define DAYTIME_SERVER_PORT 13

/ ... 的/     int main(void)     {         int serverFd,connectionFd;         struct sockaddr_in servaddr;         char timebuffer [MAX_BUFFER + 1];         time_t currenTime;

    serverFd = socket(AF_INET, SOCK_STREAM, 0);

    memset(&servaddr, 0 , sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(DAYTIME_SERVER_PORT);

    bind(serverFd, (struct sockaddr *) &servaddr, sizeof(servaddr));
    listen(serverFd, 5);

    while(1)
    {
        connectionFd = accept(serverFd, (struct sockaddr *) NULL, NULL);

        if(connectionFd >= 0)
        {
            currenTime = time(NULL);
            snprintf(timebuffer, MAX_BUFFER, "%s\n", ctime(&currenTime));
            write(connectionFd, timebuffer, strlen(timebuffer));
            close(connectionFd);
        }
    }
}

client.c

#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <string.h>

#define MAX_BUFFER 128
#define DAYTIME_SERVER_PORT 13


int main()
{
    int connectionFd, in;
    struct sockaddr_in servaddr;
    char timebuffer[MAX_BUFFER+1];

    connectionFd = socket(AF_INET,SOCK_STREAM,0);

    memset(&servaddr,0 ,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(DAYTIME_SERVER_PORT);
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    connect(connectionFd,(struct sockaddr_in *) &servaddr , sizeof(servaddr));

    while((in = read(connectionFd, timebuffer, MAX_BUFFER)) >0)
    {
        timebuffer[in] = 0;
        printf("\n%s" , timebuffer);
    }
    /*...*/
    close(connectionFd);

}

如何修改服务器以侦听环回接口(不是其他接口)?

1 个答案:

答案 0 :(得分:0)

更改

servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

只使用循环返回地址。即。

servaddr.sin_addr.s_addr = htonl(2130706433L)

(使用http://www.smartconversion.com/unit_conversion/IP_Address_Converter.aspx进行数学运算)