Skip to content

Instantly share code, notes, and snippets.

@gitsrc
Created June 13, 2019 05:53
Show Gist options
  • Select an option

  • Save gitsrc/63a15319cdc252212e4ef51553c099d3 to your computer and use it in GitHub Desktop.

Select an option

Save gitsrc/63a15319cdc252212e4ef51553c099d3 to your computer and use it in GitHub Desktop.
linux c send udp
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include "../common/common.h"
int sendUdpPackage(char *udpPackage, Config_INI *config) {
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
int isContinue = 1; //函数是否继续执行标志 : 1->继续 ,0->终止
in_addr_t in_addr = inet_addr(config->udpHost);
//如果IP解析失败则尝试域名解析
if (in_addr == INADDR_NONE) {
struct hostent *hp = NULL;
//如果解析域名失败
if ((hp = gethostbyname(config->udpHost)) == NULL) {
TRACE_INFO("ip parse and dns resolver error.\n");
isContinue = 0;
} else {
if (hp->h_length != 4) {
//目前只支持IPV4
TRACE_INFO("only support IPV4.\n");
isContinue = 0;
} else {
memcpy(&servaddr.sin_addr, hp->h_addr_list[0], hp->h_length);
}
}
} else {
servaddr.sin_addr.s_addr = in_addr;
}
//如果到目前已经不能继续执行,则返回
if (!isContinue) {
return 0;
}
servaddr.sin_port = htons(config->udpPort);
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
TRACE_INFO("cannot open udp socket.\n");
return 0;
}
if (sendto(fd, udpPackage, strlen(udpPackage), 0, // +1 to include terminator
(struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
TRACE_INFO("send udp message fail.\n");
close(fd);
return 0;
}
close(fd);
return 1;
}
@gitsrc

gitsrc commented Jun 13, 2019

Copy link
Copy Markdown
Author

linux 发送UDP ,兼容IP和域名

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment