服务端
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
int main (int argc ,char **argv)
{
int soc_ip;
int acc_ip;
int n_read;
char readBuf[128]={0};
char writeBuf[128]={0};
struct sockaddr_in sock_b;
struct sockaddr_in acc_t;
memset(&sock_b,0,sizeof(struct sockaddr_in));
memset(&acc_t,0,sizeof(struct sockaddr_in));
soc_ip=socket(AF_INET,SOCK_STREAM,0);
if(soc_ip==-1){
perror("scoket");
exit(-1);
}
sock_b.sin_family=AF_INET;
sock_b.sin_port=htons(atoi(argv[2]));
// int inet_aton(const char* straddr,struct in_addr *addrp);
inet_aton(argv[1],&sock_b.sin_addr);
bind(soc_ip,(struct sockaddr*)&sock_b,sizeof( struct sockaddr_in));
listen(soc_ip,10);
int addlen=sizeof(struct sockaddr);
while(1){
acc_ip=accept(soc_ip,(struct sockaddr *)&acc_t,&addlen);
if(acc_ip==-1){
perror("accept");
exit(-1);
}else{
printf("client ip=%s\n",inet_ntoa(acc_t.sin_addr));
}
if(fork()==0){
if(fork()==0){
while(1){
memset(&writeBuf,0,strlen(writeBuf));
printf("input: \n");
gets(writeBuf);
write(acc_ip,writeBuf,strlen(writeBuf));
}
}
while(1){
memset(&readBuf,0,strlen(readBuf));
n_read=read(acc_ip,&readBuf,128);
if(n_read==-1){
perror("read");
exit(-1);
}else{
printf("size=%d form client=%s\n",n_read,readBuf);
}
}
}
}
return 0;
}
客户端
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
int main (int argc ,char **argv)
{
int soc_ip;
int acc_ip;
int n_write;
int n_read;
char readBuf[128]={0};
char writeBuf[128]={0};
struct sockaddr_in sock_b;
struct sockaddr_in acc_t;
memset(&sock_b,0,sizeof(struct sockaddr_in));
memset(&acc_t,0,sizeof(struct sockaddr_in));
soc_ip=socket(AF_INET,SOCK_STREAM,0);
if(soc_ip==-1){
perror("scoket");
exit(-1);
}
sock_b.sin_family=AF_INET;
sock_b.sin_port=htons(atoi(argv[2]));
// int inet_aton(const char* straddr,struct in_addr *addrp);
inet_aton(argv[1],&sock_b.sin_addr);
int addlen=sizeof(struct sockaddr_in);
if(connect(soc_ip,(struct sockaddr*)&sock_b,addlen)==-1){
perror("connect");
exit(-1);
}
while(1){
if(fork()==0){
while(1){
memset(&writeBuf,0,strlen(writeBuf));
printf("input: \n");
gets(writeBuf);
n_write=write(soc_ip,writeBuf,strlen(writeBuf));
}
}
while(1){
memset(&readBuf,0,strlen(readBuf));
n_read=read(soc_ip,&readBuf,128);
if(n_read==-1){
perror("read");
exit(-1);
}else{
printf("size=%d form client=%s\n",n_read,readBuf);
}
}
}
return 0;
}
本项目是学习时的项目,由于水平有限如有错误希望留言