TCP客户端实现
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
#include <sys/socket.h>
int main(int argc, const char *argv[])
{
int fp=socket(AF_INET,SOCK_STREAM,0);
if(fp==-1)
{perror("socket");
return -1;
}
struct sockaddr_in fel={AF_INET,htons(8888),inet_addr("192.168.125.136")};
if(connect(fp,(struct sockaddr*)&fel,sizeof(fel))==-1)
{perror("connect");
return -1;
}
char wbuf[128]="";
char fbuf[128]="";
while(1)
{
bzero(wbuf,sizeof(wbuf));
bzero(fbuf,sizeof(fbuf));
fgets(wbuf,sizeof(wbuf),stdin);
wbuf[strlen(wbuf)-1]='0';
send(fp,wbuf,sizeof(wbuf),0);
recv(fp,fbuf,sizeof(fbuf),0);
printf("%s\n",fbuf);
}
close(fp);
return 0;
}
UDP服务器实现
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
#include <sys/socket.h>
int main(int argc, const char *argv[])
{
int fel=socket(AF_INET,SOCK_DGRAM,0);
if(fel==-1)
{
perror("socket");
return -1;
}
struct sockaddr_in add;
add.sin_family=AF_INET;
add.sin_port=htons(8888);
add.sin_addr.s_addr=inet_addr("192.168.125.136");
if(bind(fel,(struct sockaddr*)&add,sizeof(add))==-1)
{
perror("bind");
return -1;
}
char buf[128]="";
socklen_t len=sizeof(add);
while(1)
{
bzero(buf,sizeof(buf));
recvfrom(fel,buf,sizeof(buf),0,(struct sockaddr*)&add,&len);
printf("[%s:%d]:发送请求...\n",inet_ntoa(add.sin_addr),ntohs(add.sin_port));
strcat(buf,"felok");
sendto(fel,buf,sizeof(buf),0,(struct sockaddr*)&add,len);
printf("%s\n",buf);
}
close(fel);
return 0;
}