UDP的send、sendto和sendmsg测试代码

            #include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <linux/in.h>

void udp_test(int mode, const char *saddr,unsigned short port, const char* text)
{
        int s = socket(AF_INET,SOCK_DGRAM,0);
        if(s < 0)
        {
                printf("socket failed: %d\n",s);
                return;
        }

        struct sockaddr_in sin;
        sin.sin_family = AF_INET;
        sin.sin_port = htons(port);
        sin.sin_addr.s_addr = inet_addr(saddr);

        int len = strlen(text);
        int ret = 0;

        if(mode == 0)
        {
                ret = sendto(s,text,len,0,(struct sockaddr*)&sin,sizeof(sin));
        }else if(mode == 1)
        {
                struct msghdr msg;
                struct iovec iov;

                msg.msg_name = &sin;
                msg.msg_namelen = sizeof(sin);
                msg.msg_iov = &iov;
                msg.msg_iovlen = 1;
                msg.msg_iov->iov_base = (char*)text;
                msg.msg_iov->iov_len = len;
                msg.msg_control = 0;
                msg.msg_controllen = 0;
                msg.msg_flags = 0;

                ret = sendmsg(s,&msg,0);
        }else if(mode == 2)
        {
                if(connect(s,(struct sockaddr*)&sin,sizeof(sin))<0)
                {            printf("socket failed: %d",errno);
                        return;
                }

                ret = send(s,text,len,0);
        }

        printf("send %d byte to %s:%hu\n",ret,saddr,port);

        close(s);
}

int main(int argc,const char **argv)
{
        if(argc < 5)
        {
                return 1;
        }

        int msgid = atoi(argv[1]);

        udp_test(atoi(argv[1]),argv[2],atoi(argv[3]),argv[4]);

        return 0;
}


 

你可能感兴趣的:(UDP的send、sendto和sendmsg测试代码)