linux网络编程客户端实现client.c
程序员文章站
2022-05-18 16:33:44
...
client.c
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <string.h>
#define SERV_IP "127.0.0.1"
#define SERV_PORT 6666
int main(void)
{
int cfd;
struct sockaddr_in serv_addr;
char buf[BUFSIZ];
int n;
cfd=socket(AF_INET,SOCK_STREAM,0);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(SERV_PORT);//把本地字节序转化为网络字节序
inet_pton(AF_INET,SERV_IP,&serv_addr.sin_addr.s_addr);
connect(cfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
while(1){
fgets(buf,sizeof(buf),stdin);//hello world --- fgets --->"hello world\n\0"
write(cfd,buf,strlen(buf));
n=read(cfd,buf,sizeof(buf));
write(STDOUT_FILENO,buf,n);
}
close(cfd);
return 0;
}
server.c
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <ctype.h>
#include <arpa/inet.h>
#define SERV_IP "127.0.0.1"
#define SERV_PORT 6666
int main(void)
{
int lfd,cfd;
struct sockaddr_in serv_addr,clie_addr;
socklen_t clie_addr_len;
char buf[BUFSIZ],clie_IP[BUFSIZ];
int n,i;
lfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(SERV_PORT);//把本地字节序转化为网络字节序
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);//翻译为本地任意字节序
bind(lfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
listen(lfd,128);
clie_addr_len=sizeof(clie_addr);
cfd=accept(lfd,(struct sockaddr *)&clie_addr,&clie_addr_len);
printf("client IP:%s,client port:%d\n",
inet_ntop(AF_INET,&clie_addr.sin_addr.s_addr,clie_IP,sizeof(clie_IP)),
ntohs(clie_addr.sin_port));
while(1){
n=read(cfd,buf,sizeof(buf));
for(i=0;i<n;i++)
buf[i]=toupper(buf[i]);
write(cfd,buf,n);
}
close(lfd);
close(cfd);
return 0;
}
启动两个终端,在server终端上输入:
gcc -pthread server.c
./server
在client终端上输入:
gcc -pthread client.c
./client
上一篇: 运算符重载
下一篇: 剑指offer-Code04-矩阵查找数