gpt4 book ai didi

c - 修改服务器,使其仅监听环回接口(interface)

转载 作者:行者123 更新时间:2023-11-30 17:27:08 26 4
gpt4 key购买 nike

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

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 主函数(无效) { int serverFd, 连接Fd; struct sockaddr_in servaddr; 字符时间缓冲区[MAX_BUFFER+1]; time_t 当前时间;

    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);

}

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

最佳答案

改变

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 进行数学计算)

关于c - 修改服务器,使其仅监听环回接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26500197/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com