c语言 sendto函数,在sendto()函数中发送一个结构 - C语言

所以我尝试使用sendto()函数向客户端发送消息。在sendto()函数中发送一个结构 - C语言

和sendto()函数的原型是这样的:

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,

const struct sockaddr *dest_addr, socklen_t addrlen);

但我想送一个结构作为第二个参数。我能做到吗?或者buf必须是一个字符串?

编辑:你看,我都能够发送这样的:

“的消息由‘标题’,其次是‘有效载荷’

你的消息头应该包括以下内容:

uint8_t version; /* must be 1. If you receive anything else, discard*/

uint8_t ttl; /* must be 1. If you receive anything else, discard*/

uint16_t payload_length; /* bytes following the header */

uint32_t account_identifier; /* digits of your account name */

uint32_t source_address; /* unused for now, set to 0 and ignore. */

uint32_t destination_address; /* unused for now, set to 0 and ignore. */

uint16_t checksum; /* unused for now, set to 0 and ignore. */

uint16_t protocol; /* must be 1. If you receive anything else, discard*/"

和有效载荷是一个文本字符串,如“你好”之类的。

我觉得像我送头将发送所有的结构的唯一方式信息。对?

2014-10-19

umdcoder

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个关于编程的问题,我可以为您提供帮助。以下是一个简单的 C 语言函数,用于连接至 NTP 服务器并获取当前时间。具体实现可能会因服务器而异。请注意,在使用此代码之前,您需要先安装相关的开发库并确保您的设备可以连接到互联网。 ``` #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <time.h> /** * 连接到 NTP 服务器并获取当前时间 * * @param hostname NTP 服务器的主机名或 IP 地址 * @return 当前时间的时间戳,以秒为单位,如果无法连接到服务器,则返回 -1 */ long ntp_get_time(char* hostname) { int sockfd; char buffer[48] = {0}; struct sockaddr_in servaddr; struct hostent *server; long timestamp; // 创建 socket sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sockfd < 0) { perror("socket error"); return -1; } // 获取服务器的 IP 地址 server = gethostbyname(hostname); if (server == NULL) { perror("gethostbyname error"); return -1; } // 设置服务器地址 bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&servaddr.sin_addr.s_addr, server->h_length); servaddr.sin_port = htons(123); // NTP 端口号 // 发送 NTP 请求 buffer[0] = 0x1B; // NTP 协议版本号、模式等信息 if (sendto(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { perror("sendto error"); return -1; } // 接收服务器的响应 if (recv(sockfd, buffer, sizeof(buffer), 0) < 0) { perror("recv error"); return -1; } // 解析服务器响应的时间戳 timestamp = ntohs(*(unsigned short*)&buffer[40]); // 获取秒数 timestamp -= 2208988800UL; // 将 1900 年 1 月 1 日作为起始时间 return timestamp; } ``` 该函数使用 UDP 协议连接至 NTP 服务器,发送时间同步请求并解析服务器的响应,最后返回以秒为单位的当前时间戳。如果无法连接到服务器,则返回 -1。请记得为此函数添加必要的注释。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值