跳至主要内容

【转】udp编程实例

UDP通讯实例

2008-04-29 15:30:05 / 个人分类:linux C编程

UDP协议的几点好处:
1.UDP不要求保持一个连接;
2.UDP没有因接收方认可收到数据包(或者当数据包没有正确抵达而自动重传)而带来的开销;
3.设计UDP的目的是用于短应用和控制信息;
4.在一个数据包接一个数据包的基础上,UDP要求的网络带宽比TCP更小。
UDP的几个缺点:
1.程序员必须创建代码检测传输错误并进行重传(如果应用程序要求这样做);
2.程序员必须把大数据包分片。

code:
<1>
/*
* sender.c--UDP protocol example
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int port = 6789;

int main()
{
    int socket_descrīptor;
    int iter = 0;
    char buf[80];
    struct sockaddr_in address;

    /* Initialize socket address structure for Interner Protocols */
    bzero(&address, sizeof(address)); // empty data structure
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr("127.0.0.1");
    address.sin_port = htons(port);

    /* Create a UDP socket */
    socket_descrīptor = socket(AF_INET, SOCK_DGRAM, 0);

    //Loop 20 times (a nice round number ) sending data
    for(iter = 0; iter <= 20; iter++)
    {
        sprintf(buf, "data packet with ID %d\n", iter);
        sendto(socket_descrīptor, buf, sizeof(buf), 0, (struct sockaddr *)&address, sizeof(address));
    }   

    /* send a termination message */
    sprintf(buf, "stop\n");
    sendto(socket_descrīptor, buf, sizeof(buf), 0, (struct sockaddr *)&address, sizeof(address)); //address is the target of the message send
   
    close (socket_descrīptor);
    printf("Message Sent, Terminating\n");
    return 0;
}

<2>
/*
* receiver.c--received of the UDP protocol
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int port = 6789;

int main()
{
    int sin_len;
    char message[256];
    int socket_descrīptor;
    struct sockaddr_in sin;
    printf("Waiting for data from sender\n");

    // Initialize socket address structure for Internet Protocols
    bzero(&sin, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = htonl(INADDR_ANY);
    sin.sin_port = htons(port);
    sin_len = sizeof(sin);

    //Create a UDP socket and bind it to the port
    socket_descrīptor = socket(AF_INET, SOCK_DGRAM, 0);
    bind(socket_descrīptor, (struct sockaddr *)&sin, sizeof(sin));
   
    //Loop forever (or until a termination message is received)
    // Received data through the socket and process it.The processing in this program is really simple --printing
    while(1)
    {
        recvfrom(socket_descrīptor, message, sizeof(message), 0, (struct sockaddr *)&sin, &sin_len);
        printf("Response from server : %s\n", message);
        if(strncmp(message, "stop", 4) == 0)
        {
            printf("sender has told me to end the connection\n");
            break;
        }
    }
    close(socket_descrīptor);
    return 0;
}

分别编译产生sender、receiver两个可执行文件。
然后在两个终端中分别一次运行,可以得到结果如下:
[hyj@localhost udp_]$ ./receiver
Waiting for data from sender
Response from server : data packet with ID 0

Response from server : data packet with ID 1

Response from server : data packet with ID 2

Response from server : data packet with ID 3

Response from server : data packet with ID 4

Response from server : data packet with ID 5

Response from server : data packet with ID 6

Response from server : data packet with ID 7

Response from server : data packet with ID 8

Response from server : data packet with ID 9

Response from server : data packet with ID 10

Response from server : data packet with ID 11

Response from server : data packet with ID 12

Response from server : data packet with ID 13

Response from server : data packet with ID 14

Response from server : data packet with ID 15

Response from server : data packet with ID 16

Response from server : data packet with ID 17

Response from server : data packet with ID 18

Response from server : data packet with ID 19

Response from server : data packet with ID 20

Response from server : stop

sender has told me to end the connection
发送端结果:
[hyj@localhost udp_]$ ./sender
Message Sent, Terminating


说明:
    sendto函数同send函数,该函数通过套接口发送一条消息。此时使用了无连接的套接口;消息发送的目的地址由address指定;
    recfrom函数同sendto。注意:对于TCP和UDP你都可以使用recvfrom函数,但是recv只能用于TCP;
    此外,如果在编译时提示找不到socket函数,那么在编译时是需要指定Internet库,在gcc命令中加入-lxnet选项,如:CC -o sender sender.c -lxnet

    bind函数给套接口分配一个地址;
    函数recvfrom等待来自于无连接套接口的一个数据包。它也在地址数据结构中返回发送方的地址。这个源地址在示例程序中没有用,但是更高级的程序能够用它打开一个返回发送方的套接口。如果你不关心这个地址,可以给参数传递NULL。

    以上代码未加入任何错误处理程序,加入最少错误检测后的代码如下:
/*
* receiver2.c--received of the UDP protocol,add the error check
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

int port = 6789;

int main()
{
    int sin_len;
    char message[256];
    int socket_descrīptor;
    struct sockaddr_in sin;

    int bind_rc, close_rc;
    ssize_t recv_rc;

    printf("Waiting for data from sender\n");

    // Initialize socket address structure for Internet Protocols
    bzero(&sin, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = htonl(INADDR_ANY);
    sin.sin_port = htons(port);
    sin_len = sizeof(sin);

    //Create a UDP socket and bind it to the port
    socket_descrīptor = socket(AF_INET, SOCK_DGRAM, 0);
    if(socket_descrīptor == -1)
    {
        perror("socket call failed");
        exit(errno);
    }

    bind_rc = bind(socket_descrīptor, (struct sockaddr *)&sin, sizeof(sin));
    if(bind_rc == -1)
    {
        perror("bind call failed");
        exit(errno);
    }
   
    //Loop forever (or until a termination message is received)
    // Received data through the socket and process it.The processing in this program is really simple --printing
    while(1)
    {
        recv_rc = recvfrom(socket_descrīptor, message, sizeof(message), 0, (struct sockaddr *)&sin, &sin_len);
        if(recv_rc == -1)
        {
            perror("bind call failed");
            exit(errno);
        }
        printf("Response from server : %s\n", message);
        if(strncmp(message, "stop", 4) == 0)
        {
            printf("sender has told me to end the connection\n");
            break;
        }
    }
    close_rc = close(socket_descrīptor);
    if(close_rc == -1)
    {
        perror("close call failed");
        exit(errno);
    }
    return 0;
}


/*
* sender2.c--UDP protocol example, add the erro check
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

int port = 6789;

int main()
{
    int socket_descrīptor;
    int iter = 0;

    ssize_t sendto_rc;
    int close_rc;

    char buf[80];
    struct sockaddr_in address;
    struct hostent *hostbyname;

    //Translate a host name to IP address
    hostbyname = gethostbyname("127.0.0.1");
    if(hostbyname == NULL)
    {
        perror("Gethostbyname failed");
        exit(errno);
    }

    /* Initialize socket address structure for Interner Protocols.The address comes from the datastructure returned by gethostbyname() */
    bzero(&address, sizeof(address)); // empty data structure
    address.sin_family = AF_INET;

    memcpy(&address.sin_addr.s_addr, hostbyname->h_addr, sizeof(address.sin_addr.s_addr));

    //print the host IP
    printf("The host IP is %s\n", inet_ntoa(*(struct in_addr*)hostbyname->h_addr));   

    //address.sin_addr.s_addr = inet_addr("127.0.0.1");
    address.sin_port = htons(port);

    /* Create a UDP socket */
    socket_descrīptor = socket(AF_INET, SOCK_DGRAM, 0);
    if(socket_descrīptor == -1)
    {
        perror("socket call failed");
        exit(errno);
    }

    //Loop 20 times (a nice round number ) sending data
    for(iter = 0; iter <= 20; iter++)
    {
        sprintf(buf, "data packet with ID %d\n", iter);
        sendto_rc = sendto(socket_descrīptor, buf, sizeof(buf), 0, (struct sockaddr *)&address, sizeof(address));
        if(sendto_rc == -1)
        {
            perror("sendto call failed");
            exit(errno);
        }
    }   

    /* send a termination message */
    sprintf(buf, "stop\n");
    sendto_rc = sendto(socket_descrīptor, buf, sizeof(buf), 0, (struct sockaddr *)&address, sizeof(address)); //address is the target of the message send
    if(sendto_rc == -1)
    {
        perror("sendto  STOP call failed");
        exit(errno);
    }
   

    //Most people don''t bother to check the return code returned by the close function
    close_rc = close (socket_descrīptor);
    if(close_rc == -1)
    {
        perror("close call failed");
        exit(errno);
    }

    printf("Message Sent, Terminating\n");
    return 0;
}
   下面使用非阻塞I/O来对上面的接收程序做一些修改:
/*
* sender3.c--UDP protocol example, add the erro check,use sleep
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

int port = 6789;

int main()
{
    int socket_descrīptor;
    int iter = 0;

    ssize_t sendto_rc;
    int close_rc;

    char buf[80];
    struct sockaddr_in address;
    struct hostent *hostbyname;

    //Translate a host name to IP address
    hostbyname = gethostbyname("127.0.0.1");
    if(hostbyname == NULL)
    {
        perror("Gethostbyname failed");
        exit(errno);
    }

    /* Initialize socket address structure for Interner Protocols.The address comes from the datastructure returned by gethostbyname() */
    bzero(&address, sizeof(address)); // empty data structure
    address.sin_family = AF_INET;

    memcpy(&address.sin_addr.s_addr, hostbyname->h_addr, sizeof(address.sin_addr.s_addr));

    //print the host IP
    printf("The host IP is %s\n", inet_ntoa(*(struct in_addr*)hostbyname->h_addr));   

    //address.sin_addr.s_addr = inet_addr("127.0.0.1");
    address.sin_port = htons(port);

    /* Create a UDP socket */
    socket_descrīptor = socket(AF_INET, SOCK_DGRAM, 0);
    if(socket_descrīptor == -1)
    {
        perror("socket call failed");
        exit(errno);
    }

    //Loop 20 times (a nice round number ) sending data
    for(iter = 0; iter <= 20; iter++)
    {
        sprintf(buf, "data packet with ID %d\n", iter);
        sendto_rc = sendto(socket_descrīptor, buf, sizeof(buf), 0, (struct sockaddr *)&address, sizeof(address));
        if(sendto_rc == -1)
        {
            perror("sendto call failed");
            exit(errno);
        }
       
        sleep(3); //this is the only difference form sender2.c
       
    }   

    /* send a termination message */
    sprintf(buf, "stop\n");
    sendto_rc = sendto(socket_descrīptor, buf, sizeof(buf), 0, (struct sockaddr *)&address, sizeof(address)); //address is the target of the message send
    if(sendto_rc == -1)
    {
        perror("sendto  STOP call failed");
        exit(errno);
    }
   

    //Most people don''t bother to check the return code returned by the close function
    close_rc = close (socket_descrīptor);
    if(close_rc == -1)
    {
        perror("close call failed");
        exit(errno);
    }

    printf("Message Sent, Terminating\n");
    return 0;
}

/*
* receiver3.c--received of the UDP protocol,add the error check,this have some I/O no-blocking
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <fcntl.h>

int port = 6789;

int main()
{
    int sin_len;
    char message[256];
    int socket_descrīptor;
    struct sockaddr_in sin;

    int bind_rc, close_rc;
    ssize_t recv_rc;

    long save_file_flags;

    printf("Waiting for data from sender\n");

    // Initialize socket address structure for Internet Protocols
    bzero(&sin, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = htonl(INADDR_ANY);
    sin.sin_port = htons(port);
    sin_len = sizeof(sin);

    //Create a UDP socket and bind it to the port
    socket_descrīptor = socket(AF_INET, SOCK_DGRAM, 0);
    if(socket_descrīptor == -1)
    {
        perror("socket call failed");
        exit(errno);
    }

    bind_rc = bind(socket_descrīptor, (struct sockaddr *)&sin, sizeof(sin));
    if(bind_rc == -1)
    {
        perror("bind call failed");
        exit(errno);
    }

    //set socket to non-blocking
    save_file_flags = fcntl(socket_descrīptor, F_GETFL);
    printf("file flags are %ld\n", save_file_flags);
    save_file_flags |= O_NONBLOCK;

    if(fcntl(socket_descrīptor, F_SETFL, save_file_flags) == -1)
    {
        perror("trying to set input socket to non-blocking");
        exit(errno);
    }

    printf("file flags are now %ld\n", save_file_flags);
   
    //Loop forever (or until a termination message is received)
    // Received data through the socket and process it.The processing in this program is really simple --printing
    while(1)
    {
        sleep(1);  //wait a moment ...

        recv_rc = recvfrom(socket_descrīptor, message, sizeof(message), 0, (struct sockaddr *)&sin, &sin_len);
        if(recv_rc == -1 && errno != EAGAIN)
        {
            fprintf(stderr, "errno %d ", errno);
            perror("recvform call failed");
            exit(errno);
        }
        else if(recv_rc == 0 | errno == EAGAIN) //no data
        {
            printf("no data yet\n");
            errno = 0; // clear the error
            continue;
        }
   
        errno = 0; // clear the error
        printf("Response from server : %s\n", message);
        if(strncmp(message, "stop", 4) == 0)
        {
            printf("sender has told me to end the connection\n");
            break;
        }
    }
    close_rc = close(socket_descrīptor);
    if(close_rc == -1)
    {
        perror("close call failed");
        exit(errno);
    }
    return 0;
}

    receiver3.c中最重要的新内容是fcntl调用,它允许对打开文件的控制标志做修改。带有参数F_GETEL的第一个调用用来取得当前控制标志的状态。然后O_NONBLOCK标志被添加到当前标志中。带有参数F_SETFL的跌入个调用实际上改变了标志。一旦这一步成功完成,对套接口的读取(recvfrom)操作就不再等候数据了。当然,程序要可是fcntl的第二次调用是成功的。
    最终执行的结果如下:
[hyj@localhost udp_]$ ./sender3
The host IP is 127.0.0.1
Message Sent, Terminating


[hyj@localhost udp_]$ ./receiver3
Waiting for data from sender
file flags are 2
file flags are now 2050
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
no data yet
Response from server : data packet with ID 0

no data yet
no data yet
Response from server : data packet with ID 1

no data yet
no data yet
Response from server : data packet with ID 2

no data yet
no data yet
Response from server : data packet with ID 3

no data yet
no data yet
Response from server : data packet with ID 4

no data yet
no data yet
Response from server : data packet with ID 5

no data yet
no data yet
Response from server : data packet with ID 6

no data yet
no data yet
Response from server : data packet with ID 7

no data yet
no data yet
Response from server : data packet with ID 8

no data yet
no data yet
Response from server : data packet with ID 9

no data yet
no data yet
Response from server : data packet with ID 10

no data yet
no data yet
Response from server : data packet with ID 11

no data yet
no data yet
Response from server : data packet with ID 12

no data yet
no data yet
Response from server : data packet with ID 13

no data yet
no data yet
Response from server : data packet with ID 14

no data yet
no data yet
Response from server : data packet with ID 15

no data yet
no data yet
Response from server : data packet with ID 16

no data yet
no data yet
Response from server : data packet with ID 17

no data yet
no data yet
Response from server : data packet with ID 18

no data yet
no data yet
Response from server : data packet with ID 19

no data yet
no data yet
Response from server : data packet with ID 20

no data yet
no data yet
Response from server : stop

sender has told me to end the connection

评论

此博客中的热门博文

【转】嵌入式开发中使用DDD进行调试

 在嵌入式程序开发过程中,程序员要进行大量的调试,以此验证程序的正确性,修改潜在的错误。调试器对于程序员来说是不可或缺的必备工具。在Linux环境中,有很多调试工具和调试辅助工具,例如GDB、XXGDB、RHIDE、XWPE、GVD和DDD等。其中,DDD是命令行调试器的图形前端,除了一般的程序调试功能以外,还具有交互式图形数据显示的功能。它在嵌入式应用开发中也十分出色。本文主要讲述DDD(Data Display Debugger)的使用方法。      1.认识DDD     GNU DDD是命令行调试程序,如GDB、DBX、WDB、Ladebug、JDB、XDB、Perl Debugger或Python Debugger的可视化图形前端。它特有的图形数据显示功能(Graphical Data Display)可以把数据结构按照图形的方式显示出来。DDD最初源于1990年Andreas Zeller编写的VSL结构化语言,后来经过一些程序员的努力,演化成今天的模样。DDD的功能非常强大,可以调试用C\C++、Ada、 Fortran、Pascal、Modula-2和Modula-3编写的程序;可以超文本方式浏览源代码;能够进行断点设置、回溯调试和历史纪录编辑;具有程序在终端运行的仿真窗口,并在远程主机上进行调试的能力;图形数据显示功能(Graphical Data Display)是创建该调试器的初衷之一,能够显示各种数据结构之间的关系,并将数据结构以图形化形式显示;具有GDB/DBX/XDB的命令行界面,包括完全的文本编辑、历史纪录、搜寻引擎。     DDD是开源软件,用户可以去 http://www.cs.tubs.de/softech/ddd/ 下载.rpm格式的DDD源码文件。      图1显示的是DDD的主窗口。它主要由选单栏、工具条、数据窗口、源文件窗口、机器码窗口、控制台和命令工具窗口等几部分组成。其中,数据窗口用于观察复杂的数据结构,在删除数据之后,显示仍然有效;源文件窗口显示源代码、断点和当前执行到达的位置,选择该窗口中的"Display"项,可以显示任意表达式的值;机...

【转】cs8900网卡的移植至基于linux2.6内核的s3c2410平台

cs8900网卡的移植至基于linux2.6内核的s3c2410平台(转) 2008-03-11 20:58 硬件环境:SBC-2410X开发板(CPU:S3C2410X) 内核版本:2.6.11.1 运行环境:Debian2.6.8 交叉编译环境:gcc-3.3.4-glibc-2.3.3 第一部分 网卡CS8900A驱动程序的移植 一、从网上将Linux内核源代码下载到本机上,并将其解压: #tar jxf linux-2.6.11.1.tar.bz2 二、打开内核顶层目录中的Makefile文件,这个文件中需要修改的内容包括以下两个方面。 (1)指定目标平台。 移植前:         ARCH?= $(SUBARCH) 移植后: ARCH            :=arm (2)指定交叉编译器。 移植前: CROSS_COMPILE ?= 移植后: CROSS_COMPILE   :=/opt/crosstool/arm-s3c2410-linux-gnu/gcc-3.3.4-glibc-2.3.3/bin/arm-s3c2410-linux-gnu- 注:这里假设编译器就放在本机的那个目录下。 三、添加驱动程序源代码,这涉及到以下几个方面。(1)、从网上下载了cs8900.c和cs8900.h两个针对2.6.7的内核的驱动程序源代码,将其放在drivers/net/arm/目录下面。 #cp cs8900.c ./drivers/net/arm/ #cp cs8900.h ./drivers/net/arm/ 并在cs8900_probe()函数中,memset (&priv,0,sizeof (cs8900_t));函数之后添加如下两条语句: __raw_writel(0x2211d110,S3C2410_BWSCON); __raw_writel(0x1f7c,S3C2410_BANKCON3); 注:其原因在"第二部分"解释。 (2)、修改drivers/net/arm/目录下的Kconfig文件,在最后添加如...

【转】函数指针和指针函数

【函数指针】        在程序运行中,函数代码是程序的算法指令部分,它们和数组一样也占用存储空间,都有相应的地址。可以使用指针变量指向数组的首地址,也可以使用指针变量指向函数代码的首地址,指向函数代码首地址的指针变量称为函数指针。 1.函数指针定义 函数类型 (*指针变量名)(形参列表); "函数类型"说明函数的返回类型,由于"()"的优先级高于"*",所以指针变量名外的括号必不可少,后面的"形参列表"表示指针变量指向的函数所带的参数列表。 例如: int (*f)(int x); double (*ptr)(double x); 在定义函数指针时请注意:     函数指针和它指向的函数的参数个数和类型都应该是―致的; 函数指针的类型和函数的返回值类型也必须是一致的。 2.函数指针的赋值 函数名和数组名一样代表了函数代码的首地址,因此在赋值时,直接将函数指针指向函数名就行了。 例如, int func(int x);   /* 声明一个函数 */ int (*f) (int x);    /* 声明一个函数指针 */ f=func;            /* 将func函数的首地址赋给指针f */ 赋值时函数func不带括号,也不带参数,由于func代表函数的首地址,因此经过赋值以后,指针f就指向函数func(x)的代码的首地址。 3.通过函数指针调用函数 函数指针是通过函数名及有关参数进行调用的。 与其他指针变量相类似,如果指针变量pi是指向某整型变量i的指针,则*p等于它所指的变量i;如果pf是指向某浮点型变量f的指针,则*pf就等价于它所指的变量f。同样地,*f是指向函数func(x)的指针,则*f就代表它所指向的函数func。所以在执行了f=func;之后,(*f)和func代表同一函数。 由于函数指针指向存储区中的某个函数,因此可以通过函数指针调用相应的函数。现在我们就讨论如何用函数指针调用函数,它应执行下面三步: 首先,要说明函数指针变量。 例如:int (*f)...