udp socket

编程技术  /  houtizong 发布于 3年前   80
mqq@208_181:~/fabricehao/test/20120726> cat udpserver.c #include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>int main(int argc,char * argv[]){    int s,fd,len;    struct sockaddr_in my_addr;    struct sockaddr_in remote_addr;    int sin_size;    char buf[BUFSIZ];    memset(&my_addr,0,sizeof(my_addr));    my_addr.sin_family=AF_INET;    my_addr.sin_addr.s_addr=INADDR_ANY;    my_addr.sin_port=htons(87654);        if((s=socket(AF_INET,SOCK_DGRAM,0))<0)    {        perror("socket");        return 1;    }    if(bind(s,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)    {        perror("bind");        return 1;    }    sin_size=sizeof(struct sockaddr_in);    printf("waiting for a packet ...\n");    if((len=recvfrom(s,buf,BUFSIZ,0,(struct sockaddr *)&remote_addr,&sin_size))<0)    {        perror("recvfrom ");        return 1;    }    printf("received packet from %s:\n",inet_ntoa(remote_addr.sin_addr));    buf[len]='\0';    printf("contents: %s \n",buf);    close(s);    return 0;}mqq@208_181:~/fabricehao/test/20120726> 


mqq@208_181:~/fabricehao/test/20120726> cat udpclient.c #include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>int main(int argc,char *argv[]){    int s,len;    struct sockaddr_in remote_addr;    char buf[BUFSIZ];        memset(&remote_addr,0,sizeof(remote_addr));    remote_addr.sin_family=AF_INET;    remote_addr.sin_addr.s_addr=inet_addr("127.0.0.1");    remote_addr.sin_port=htons(87654);    if((s=socket(AF_INET,SOCK_DGRAM,0))<0)    {        perror("socket");        return 1;    }    strcpy(buf,"this is a test message");    printf("sending:%s\n",buf);    if((len=sendto(s,buf,strlen(buf),0,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr)))<0)    {        perror("sendto");        return 1;    }    close(s);    return 0;}mqq@208_181:~/fabricehao/test/20120726> 

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客