c-udp套接字上的多变量
我必须通过udp套接字发送多个变量类型:int数组和char。我想用相同的udp数据包发送它。标准溶液是什么?将所有内容转换为字节或类似的内容 我使用的是:sendto(int sockfd,const void*buf,size\u t len,int flags, const struct sockaddr*dest_addr,socklen_t addrlen) 我的代码类似于:c-udp套接字上的多变量,c,sockets,C,Sockets,我必须通过udp套接字发送多个变量类型:int数组和char。我想用相同的udp数据包发送它。标准溶液是什么?将所有内容转换为字节或类似的内容 我使用的是:sendto(int sockfd,const void*buf,size\u t len,int flags, const struct sockaddr*dest_addr,socklen_t addrlen) 我的代码类似于: int buffer[100]; char flag = '0'; int i = 0; for (i =
int buffer[100];
char flag = '0';
int i = 0;
for (i = 0; i < 50; i++) {
buffer[i] = i * 2;
}
if (sendto(s, buffer, sizeof(buffer), 0, (struct sockaddr *) &si_client, slen) == -1 ){
//error
}
//rest of the program
int缓冲区[100];
字符标志='0';
int i=0;
对于(i=0;i<50;i++){
缓冲区[i]=i*2;
}
if(发送到(s,缓冲区,sizeof(缓冲区),0,(struct sockaddr*)&si_客户端,slen)=-1){
//错误
}
//节目的其余部分
是的,您需要将消息序列化为字节数组。没有接受int
数组的sendto
版本。试着这样做:
int arr[] = {1, 2, 3};
char str[] = "hello";
size_t buflen = sizeof arr + sizeof str;
char* buf = malloc(buflen);
if (NULL == buf)
abort();
unsigned i = 0;
for (unsigned j=0; j<3; ++j)
{
buf[i++] = (arr[j] >> 24) & 0x000000ff;
buf[i++] = (arr[j] >> 16) & 0x000000ff;
buf[i++] = (arr[j] >> 8) & 0x000000ff;
buf[i++] = (arr[j] >> 0) & 0x000000ff;
}
strcpy(&(buf[i]), str);
if (sendto(s, buffer, sizeof(buffer), 0, (struct sockaddr *) &si_client, slen) == -1 ){
//error
}
intarr[]={1,2,3};
char str[]=“你好”;
尺寸=arr的尺寸+str的尺寸;
char*buf=malloc(buflen);
如果(NULL==buf)
中止();
无符号i=0;
对于(无符号j=0;j>24)&0x000000ff;
buf[i++]=(arr[j]>>16)&0x000000ff;
buf[i++]=(arr[j]>>8)&0x000000ff;
buf[i++]=(arr[j]>>0)&0x000000ff;
}
strcpy(&(buf[i]),str;
if(发送到(s,缓冲区,sizeof(缓冲区),0,(struct sockaddr*)&si_客户端,slen)=-1){
//错误
}
请注意,您的消息仍可能作为多个数据包发送,例如,如果其大小超过路径MTU。通常的方法是将数据放入结构中。然后可以使用“sendto”调用一次发送整个结构 但请注意,这并不是完全可移植的。不同的系统可能会对结构进行不同的布局。为了降低发生这种情况的风险,您应该
- 布局结构,使所有值自然对齐,并且不依赖填充
- 填写结构并解释其内容时,使用“htons”、“htonl”、“ntohs”和“ntohl”宏将主机字节顺序转换为网络字节顺序,反之亦然