我正在尝试将客户端连接到服务器,因此客户端可以向服务器发送消息。 这是我的代码
服务器
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int connfd, listenfd, tmp, sin_size;
struct sockaddr_in servaddr, client;
char message[100];
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(13);
bzero(&servaddr, sizeof(servaddr));
listenfd = socket(AF_INET,SOCK_STREAM,0);
if(listenfd == -1)
{
printf("Error create socket\n");
exit(1);
}
tmp = bind(listenfd, (struct sockaddr*)&servaddr, sizeof(struct sockaddr));
if(tmp == -1)
{
printf("Error binding\n");
exit(1);
}
listen(listenfd,2);
sin_size = sizeof(client);
connfd = accept(listenfd, (struct sockaddr*)&client, &sin_size);
if(connfd == -1)
{
printf("Error accept\n");
exit(1);
}
bzero(&message, sizeof(message));
read(connfd, &message, sizeof(message));
write(connfd, message, sizeof(message));
close(connfd);
close(listenfd);
}
客户端
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv)
{
int connfd, listenfd;
int port = atoi(argv[2]);
char message[100];
listenfd = socket(AF_INET,SOCK_STREAM,0);
if(listenfd == -1)
{
printf("Error create socket\n");
exit(1);
}
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
connfd = accept(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
if(connfd == -1)
{
printf("Error accept\n");
exit(1);
}
bzero(&message, sizeof(message));
printf("Input kata: ");
scanf("%[^\n]",message);
getchar();
write(listenfd, &message, sizeof(message));
read(listenfd, &message, sizeof(message));
close(listenfd);
}
我编译并运行服务器(./server 8000),它正在等待客户端连接。 当我试图在这部分编译时出现错误
connfd = accept(listenfd,(struct sockaddr *)&amp; servaddr, 的sizeof(servaddr));
说
warning: passing argument 3 of ‘accept’ makes pointer from integer without a cast [enabled by default]
/usr/include/x86_64-linux-gnu/sys/socket.h:214:12: note: expected ‘socklen_t * __restrict__’ but argument is of type ‘long unsigned int’
我该怎么办才能修复它?
答案 0 :(得分:3)
作为警告建议你应该传递长度参数的地址而不是实际长度。
socklen_t szaddr = sizeof(servaddr);
connfd = accept(listenfd, (struct sockaddr*)&servaddr, &szaddr);