inet_pton()以及inet_ntop()的用法
#include
int inet_pton(int family, const char *strptr, void *addrptr);
//返回:若成功则为1,若输入不是有效的表达格式则为0,若出错则为-1
const char *inet_ntop(int family, const void *addrptr, char *strptr, size_t len);
//返回:若成功则为指向结果的指针, 若出错则为NULL
服务器端:
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXBUFFER 256
int main(int argc, char** argv)
{
int serverFd, connFd, ret;
socklen_t len;
struct sockaddr_in serveraddr, clientaddr;
char readBuf[MAXBUFFER] = {0};
char ip[40] = {0};
if((serverFd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
printf("socket error:%s\n",strerror(errno));
exit(-1);
}
bzero(&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(atoi(argv[2]));
inet_pton(AF_INET, argv[1], &serveraddr.sin_addr);
if((ret = bind(serverFd, (struct sockaddr*)&serveraddr, sizeof(serveraddr))) != 0){
close(serverFd);
printf("bind error:%s\n", strerror(errno));
exit(-1);
}
if((ret = listen(serverFd, 5)) != 0){
close(serverFd);
printf("listen error:%s\n",strerror(errno));
exit(-1);
}
len = sizeof(clientaddr);
bzero(&clientaddr, sizeof(clientaddr));
while(1){
connFd = accept(serverFd, (struct sockaddr*)&clientaddr, &len);
if(serverFd < 0){
printf("accept error : %s\n",strerror(errno));
continue;
}
while((ret=read(connFd,readBuf,MAXBUFFER))){
write(connFd,readBuf,MAXBUFFER);
bzero(readBuf,MAXBUFFER);
}
if(ret!=0)
{
printf("read error:%s\n",strerror(errno));
}
close(connFd);
}
close(serverFd);
return 0;
}
客户端:
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXBUFFER 256
int main(int argc, char** argv)
{
int clientFd,ret;
struct sockaddr_in serveraddr;
char buf[MAXBUFFER];
if((clientFd=socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("socket error:%s\n",strerror(errno));
exit(-1);
}
bzero(&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(atoi(argv[2]));
inet_pton(AF_INET,argv[1],&serveraddr.sin_addr);
if((ret=connect(clientFd,(struct sockaddr *)&serveraddr,sizeof(serveraddr)))!=0)
{
close(clientFd);
printf("connect error:%s\n",strerror(errno));
exit(-1);
}
while(1)
{
bzero(buf,sizeof(buf));
gets(buf);
if(buf == EOF){
return 0;
}
write(clientFd,buf,sizeof(buf));//写数据
bzero(buf,sizeof(buf));
read(clientFd,buf,sizeof(buf));//读数据
printf("%s\n",buf);
}
close(clientFd);
return (EXIT_SUCCESS);
}