[英]Sending UDP socket in linux - C language
我知道這顯然是基本問題,我知道有許多教程和現成的示例,但我必須錯過一些東西。 我正在嘗試通過UDP套接字將例如文本( char *
)發送到本地網絡中的其他計算機。 到目前為止,我嘗試了一些教程,例如http://gafferongames.com/networking-for-game-programmers/sending-and-receiving-packets/等,但是我總是在errno的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;
}
bind
被稱為本地地址(您打算將數據包recv
到的地址)。 IP地址必須是計算機的本地IP地址,或者(通常是INADDR_ANY
。
通常,您根本不需要在客戶端上使用bind
。 系統將自動為您選擇合適的空閑端口。
要為UDP套接字指定遠程地址,請使用sendto
而不是send
。
如果您在Google中搜索udp client c code
,則第一個結果是該 udp client c code
。 您可以看到聯網部分基本上只是兩個調用,即socket
和sendto
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.