在linux中发送UDP套接字 - C语言

时间:2014-04-27 09:18:10

标签: c linux sockets udp

我知道这显然是基本问题,我知道有很多教程和现成的例子,但我必须遗漏一些东西。我试图通过UDP套接字将文本(char *)发送到本地网络中的其他机器。到目前为止,我尝试了一些教程,如http://gafferongames.com/networking-for-game-programmers/sending-and-receiving-packets/等等,但我总是在bind()函数中出错,错误“无法分配请求的地址”。

我只是在char数组中有一些数据,我想通过网络将它们推送到另一台主机。有人可以指出我正确的方向吗?我需要套接字服务器或客户端吗?我是否需要将套接字绑定到某个接口?

这是我的游乐场:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <errno.h>

int handle;

int init_socket()
{
        handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

        if (handle <= 0)
        {
                printf("failed to create socket\n");
                return 1;
        }

        printf("sockets successfully initialized\n");

        return 0;
}

int main ()
{
        unsigned short port = 30000;
    char * data = "hovno";

    init_socket();

        struct sockaddr_in address;

    memset((char *) &address, 0, sizeof(address));

        address.sin_family = AF_INET;
        address.sin_addr.s_addr = inet_addr("192.168.11.129"); // this is address of host which I want to send the socket
        address.sin_port = htons(port);


    printf("handle: %d\n", handle); // prints number greater than 0 so I assume handle is initialized properly

        if (bind(handle, (const struct sockaddr*) &address, sizeof(struct sockaddr_in)) < 0)
        {
                printf("failed to bind socket (%s)\n", strerror(errno)); // Cannot assign requested address
                return 1;
        }

        int nonBlocking = 1;
        if (fcntl(handle, F_SETFL, O_NONBLOCK, nonBlocking) == -1)
        {
                printf("failed to set non-blocking\n");
                return 2;
        }

        int sent_bytes = sendto(handle, data, strlen(data), 0, (const struct sockaddr*) &address, sizeof(struct sockaddr_in));

        if (sent_bytes != strlen(data))
        {
                printf("failed to send packet\n");
                return 3;
        }

    return 0;
}

1 个答案:

答案 0 :(得分:4)

本地地址(您打算将bind个数据包发送到地址)调用

recv。 IP地址必须是计算机的本地IP地址,或(最常见)INADDR_ANY

通常,您根本不必在客户端使用bind。系统会自动为您选择合适的空闲端口。

要指定UDP套接字的远程地址,请使用sendto,而不是send

如果您在Google上搜索udp client c code,则其中一个结果是this one。您可以看到网络部分基本上只有两个电话socketsendto