//服务器端
#include <stdio.h>
//#include <linux/in.h>#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#define UDP_PORT 3000
int main(int argc,char *argv[])
{
int sfd,ret;
struct sockaddr_in sAddr,cAddr;
sfd = socket(AF_INET,SOCK_DGRAM,0);
if(sfd == -1)
{
printf("error:%s\n",strerror(errno));
return sfd;
}
sAddr.sin_family = AF_INET;
sAddr.sin_addr.s_addr = INADDR_ANY;
sAddr.sin_port = htons(UDP_PORT);
ret = bind(sfd,(sockaddr*)(&sAddr),sizeof(sAddr));
if(-1 == ret)
{
printf("error:%s\n",strerror(errno));
return ret;
}
char buf[100] = {0};
while(1)
{
socklen_t len = sizeof(sockaddr);
ssize_t s = recvfrom(sfd,buf,sizeof(buf),0,(sockaddr*)(&cAddr),&len);
if(-1 == s)
{
printf("error:%s\n",strerror(errno));
return ret;
}
if(0 != s)
{
ret = write(STDOUT_FILENO,buf,s);
if(-1 == ret)
{
printf("error:%s\n",strerror(errno));
return ret;
}
}
}
}
//客户端
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
int connectsock(const char *host,const char *service,const char* transport)
{
int sock;
struct sockaddr_in saddr ={0};
saddr.sin_family = AF_INET;
struct servent *ent = getservbyname(service,transport);
if(ent)
{
saddr.sin_port = ent->s_port;
}
else
{
if((saddr.sin_port = htons(atoi(service))) == 0)
{
printf("error!\n");
exit(-1);
}
printf("#%s=%d\n",service,saddr.sin_port);
}
struct hostent *hent = gethostbyname(host);
if(hent)
{
memcpy(&saddr.sin_addr,hent->h_addr,hent->h_length);
}
else
{
if((saddr.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE)
{
printf("error,can't get address from %s",host);
exit(-1);
}
printf("####\n");
}
int type;
struct protoent *pent = getprotobyname(transport);
if(pent)
{
if(0 == strcmp(transport,"udp"))
type = SOCK_DGRAM;
else
type = SOCK_STREAM;
sock = socket(AF_INET,type,pent->p_proto);
if(-1 == sock)
{
printf("error,socket() fail:%s",strerror(errno));
exit(-1);
}
printf("##proto:%d\n",pent->p_proto);
}
else
{
printf("can't get proto from:%s",transport);
exit(-1);
}
printf("%s:%d:%d\n",inet_ntoa(saddr.sin_addr),saddr.sin_port,pent->p_proto);
if(connect(sock,(sockaddr*)&saddr,sizeof(saddr)) == -1)
{
printf("can't connect:%s",strerror(errno));
exit(-1);
}
return sock;
}
int connectUDP(const char* host,const char* service)
{
return connectsock(host,service,"udp");
}
int connectTCP(const char* host,const char* service)
{
return connectsock(host,service,"tcp");
}
int main(int argc,char *argv[])
{
int sock = connectUDP("192.168.1.103","3000");
char buf[] = "hello";
int s = write(sock,buf,strlen(buf));
printf("size %d wrote\n",s);
}