Appearance
Code:hqyj/network/04/groupsnd.c
c
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define ERR_MSG(msg) \
do { \
fprintf(stderr, "line %d\n", __LINE__); \
perror(msg); \
} while (0)
#define PORT 2222
#define IP "224.1.2.3" // 224.0.0.0 ~ 239.255.255.255
int main(int argc, char const *argv[]) {
// 创建报式套接字
int cfd = socket(AF_INET, SOCK_DGRAM, 0);
if (cfd < 0) {
ERR_MSG("socket");
return -1;
}
printf("socket create success cfd=%d __%d__\n",
cfd, __LINE__);
// 填充服务器的地址信息结构体,绑定到套接字上
struct sockaddr_in sin;
sin.sin_family = AF_INET; // 必须填充 AF_INET
sin.sin_port = htons(PORT); // 1024~49151
sin.sin_addr.s_addr = inet_addr(IP);
char buf[128] = "";
ssize_t res = 0;
while (1) {
bzero(buf, sizeof(buf));
// 发送数据
printf("请输入>>>");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = 0;
if (sendto(cfd, buf, sizeof(buf), 0,
(struct sockaddr *)&sin, sizeof(sin)) < 0) {
ERR_MSG("sendto");
return -1;
}
printf("sendto success\n");
}
// 关闭套接字
close(cfd);
return 0;
}