我正在通过TCP创建套接字通信。
如果我关闭客户端,我在服务器端关闭newClientFd
时会收到错误,如此
cannot assign requested address
这是服务器代码:
#include<stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
int retCode = 0;
struct sockaddr_in servAddr;
pipe(cliPipe);
serverFd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == serverFd)
{
retCode = -1;
}
else
{
mem_memset(&servAddr, '\0', sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(CLI_UTIL_PORT_NUM);
if (setsockopt(serverFd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
{
perror("setsockopt(SO_REUSEADDR) failed");
retCode = -1;
}
if(bind(serverFd, (struct sockaddr*)&servAddr, sizeof(servAddr)) == -1)
{
retCode = -1;
}
else
{
listen(serverFd, 4);
}
}
newClientFd = accept(serverFd, (struct sockaddr*)NULL, NULL);
if(-1 != read(newClientFd, &cliMsgHdr, sizeof(CliMsgHdr_t)))
{printf("read success");}
write(newClientFd, &cliMsgHdr, sizeof(CliMsgHdr_t));
close(newClientFd);
return retCode;
}
以下是客户端代码:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
int retCode = 0;
struct sockaddr_in servAddr;
char *loopbackAddr = "127.0.0.1";
if(!ipaddr)
{
ipaddr = loopbackAddr;
}
if((clientFd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
retCode = -1;
}
if(RC_SUCCESS == retCode)
{
memset(&servAddr, '0', sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(CLI_UTIL_PORT_NUM);
if(inet_pton(AF_INET, ipaddr, &servAddr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
retCode = -1;
}
else if(connect(clientFd, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0)
{
printf("\n Error : Connect Failed \n");
perror("");
retCode = -1;
}
}
write(clientFd, &cliMsgHdr, sizeof(CliMsgHdr_t));
read(clientFd, &cliMsgHdr, sizeof(CliMsgHdr_t));
close(clientFd);
return retCode;
}
cliMsghdr是一种读取和发送数据的结构。