C语言实现UDP服务器,客户端

客户端

#include
#include "unistd.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "string.h"
#include "stdlib.h"

#define IP "127.0.0.1"
#define PORT 8888


int main()
{
    int fb=0,len=0;
    char buf[512]={0};
    struct sockaddr_in List_buf,from;
    len=sizeof(List_buf);
    //创建套接字
    fb = socket(AF_INET,SOCK_DGRAM,0);
    List_buf.sin_family=AF_INET;
    List_buf.sin_port=htons(PORT);
    List_buf.sin_addr.s_addr=inet_addr(IP);
    bind(fb,(struct sockaddr *)&List_buf,len);

    while(1)
    {
        //发送数据
        bzero(buf,512);
        printf("要发送的数据>>");
        fgets(buf,512,stdin);
        sendto(fb,buf,strlen(buf),0,(struct sockaddr *)&List_buf,len);
        bzero(buf,512);
        //接收数据
        recvfrom(fb,buf,512,0,(struct sockaddr *)&List_buf,&len);
        printf("收到%s发来的信息%s>>",inet_ntoa(from.sin_addr),buf);
    }

    close(fb);
    return 0;
}

服务器

#include
#include "unistd.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "string.h"
#include "stdlib.h"

#define IP "127.0.0.1"
#define PORT 8888


int main()
{
    int fb=0,len=0;
    char buf[512]={0};
    struct sockaddr_in List_buf,from;
    len=sizeof(List_buf);
    //创建套接字
    fb = socket(AF_INET,SOCK_DGRAM,0);
    List_buf.sin_family=AF_INET;
    List_buf.sin_port=htons(PORT);
    List_buf.sin_addr.s_addr=inet_addr(IP);
    bind(fb,(struct sockaddr *)&List_buf,len);

    while(1)
    {
        bzero(buf,512);
        //接收数据
        recvfrom(fb,buf,512,0,(struct sockaddr *)&from,&len);
        printf("收到%s发来的信息%s>>",inet_ntoa(from.sin_addr),buf);
        //发送数据
        bzero(buf,512);
        printf("要发送的数据>>");
        fgets(buf,512,stdin);
        sendto(fb,buf,strlen(buf),0,(struct sockaddr *)&from,len);
    }

    close(fb);
    return 0;
}

先运行服务器再运行客户端

你可能感兴趣的:(udp,服务器,c语言)