• UDP网络程序设计


    udp_server

    #include<stdio.h>
    #include<sys/socket.h>
    #include<string.h>
    #include<netinet/in.h>
    #define portnum 3333


    void main()
    {
    int n,addrlen;
    char buffer[128];
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    int sockfd;
    //1创建套接字
    sockfd=socket(AF_INET,SOCK_DGRAM,0)

    //2.1设置地址
    bzero(&server_addr,sizeof(struct sockaddr_in));
    server_addr.sin_family=AF_INET; //IPV4协议族
    server_addr.sin_port=htons(portnum);
    server_addr.sin_addr.s_addr=htonl(INADDR_ANY);

    //2绑定地址
    bind(sockfd, (struct sockaddr *)(&server_addr),sizeof(struct sockaddr));

    //3接收数据
    while(1)
    {
    addrlen=sizeof(struct sockaddr);
    bzero(buffer,sizeof(buffer));
    n= recvfrom(sockfd,buffer,128,0,(struct sockaddr *)(&client_addr),&addrlen);
    buffer[n]=0; //0是字符串的结束符
    printf("server received :%s ",buffer);

    }

    //4结束连接

    close(sockfd);

    }

    udp_client

    #include<stdio.h>
    #include<sys/socket.h>
    #include<string.h>
    #include<netinet/in.h>
    #define portnum 3333

    #define BUF_SIZE 128

    int main(int argc, char **argv)
    {
    char buffer[BUF_SIZE];
    struct sockaddr_in server_addr;
    int sockfd;

    if(argc!=2)
    {
    printf("usage:%s server_ip ",argv[0]);
    exit(1);

    }
    //1创建套接字
    sockfd=socket(AF_INET,SOCK_DGRAM,0)

    //2.1设置地址
    bzero(&server_addr,sizeof(struct sockaddr_in));
    server_addr.sin_family=AF_INET; //IPV4协议族
    server_addr.sin_port=htons(portnum);
    server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    inet_aton(argv[1],&server_addr.sin_addr);

    //2发送数据

    while(1)
    {

    printf("please input char: ");
    fgets(buffer,128,stdin);

    sendto(sockfd,buffer,strlen(buffer),0, (struct sockaddr *)(&server_addr),sizeof(struct sockaddr));
    bzero(buffer,sizeof(buffer));


    }

    //3关闭连接

    close(sockfd);
    return 0;

    }

  • 相关阅读:
    C#中静态与非静态方法比较
    Hibernate学习之路-- -映射 继承关系(subclass , joined-subclass,union-subclass )
    网络协议概述:物理层、连接层、网络层、传输层、应用层详解
    phpstorm xdebug配置
    eclipse修改内存大小
    Session机制详解
    java把html标签字符转普通字符(反转换成html标签)(摘抄)
    JAVA调用WCF
    RabbitMQ入门与使用篇
    大话程序猿眼里的高并发
  • 原文地址:https://www.cnblogs.com/1932238825qq/p/7384630.html
Copyright © 2020-2023  润新知