linux+udp+server+client

一、客户端

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<arpa/inet.h>

#include<unistd.h>

#include<stdio.h>

#include<errno.h>

#include<time.h>

#include<string.h>

void main()

{

  char send_data[20]="im sender data";

  int fd;

  struct sockaddr_in local_addr,to_addr;

  fd=socket(AF_INET,SCOK_DGRAM,0);

  if(fd<0)

  {

    printf("create socket error");

    return;

  }

  local_addr.sin_family=AF_INET;

  local_addr.sin_port=htons(7777);

  local_addr.sin_addr.s_addr=INADDR_ANY;

  to_addr.sin_family=AF_INET;

  to_addr.sin_port=htons(8888);

  to_addr.sin_addr.s_addr=INADDR_ANY;

  if(-1 == bind(fd,(struct sockaddr*)&local_addr,sizeof(local_addr)))

  {

  printf("bind error );

  close(fd);

  return;

  }

  printf("bind success");

  while(1)

  {

  sleep(1);

  if(-1 != sendto(fd,send_data,sizeof(send_data),0,(struct sockaddr*)&to_addr,sizeof(to_addr)))

    printf("send success ");

  else

    printf("send error ");

  }

}

二、服务器

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<arpa/inet.h>

#include<unistd.h>

#include<stdio.h>

#include<errno.h>

#include<time.h>

#include<string.h>

void main()

{

  int fd;

  int n;

  char rcv_buf[256];

  socklen_t servlen;

  struct sockaddr_in from_addr,temp_addr;

  fd=socket(AS_INET,SOCK_DGRAM,0);

  if(fd<0)

  {  

  printf("create socket error");

  return;

  }

  from_addr.sin_family=AF_INET;

  from_addr.sin_port=htons(8888);

  from_addr.sin_addr.s_addr=INADDR_ANY;

  servlen=sizeof(tem_addr);  

  if(-1 == bind(fd,(struck sockaddr*)&from_addr,sizeof(struck sockaddr_in)))

  {

  printf("bind error");

  return;

  }

  while(1)

  {

  bzero(rcv_buf,256);

  n=rcvfrom(fd,rcv_buf,256,0,(struct sockaddr*)&temp_addr,&servlen);

  rcv_buf[n]=0;

  printf("rcvdata:%s ",rcv_buf);

  }

}

 ps:

1、unsigned short int htons(unsigned short int hostshort);将参数指定的16位hostshort转换成网络字符顺序。

2、int inet_aton(const char * cp,struct in_addr *inp);将参数cp所指的网络地址字符串转换成网络使用的二进制的数字, 然后存于参数inp所指的in_addr结构中。

原文地址:https://www.cnblogs.com/judes/p/7115935.html