【发布时间】:2016-12-14 13:41:02
【问题描述】:
我正在尝试通过缓冲区发送单个 unsigned char。我正在使用大小为 2 的缓冲区
unsigned char temp_buf [2];
temp_buf [0]= (unsigned char) 0xff;
temp_buf [1]= NULL;
我的sendto 函数看起来像这样:
if (sendto(fd, temp_buf, sizeof (temp_buf), 0, (struct sockaddr *)&remaddr, addrlen) < 0)
perror("sendto");
它编译没有问题,但是在运行时我得到一个错误:
sendto: 无效参数
这意味着我使用的缓冲区有问题。我怀疑这个问题可能是因为我使用了 siezeof,所以我将其更改为 strlen(temp_buf) 但仍然没有运气!
编辑:我试图通过不包含整个代码来简化问题,但在这里,抱歉!
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "port.h"
#define BUFSIZE 2048
int
main(int argc, char **argv)
{
struct sockaddr_in myaddr; /* our address */
struct sockaddr_in remaddr; /* remote address */
socklen_t addrlen = sizeof(remaddr); /* length of addresses */
int recvlen; /* # bytes received */
int fd; /* our socket */
int msgcnt = 0; /* count # of messages we received */
unsigned char buf[BUFSIZE]; /* receive buffer */
/* create a UDP socket */
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("cannot create socket\n");
return 0;
}
/* bind the socket to any valid IP address and a specific port */
memset((char *)&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(SERVICE_PORT);
if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
perror("bind failed");
return 0;
}
/* now loop, receiving data and printing what we received */
printf("waiting on port %d\n", SERVICE_PORT);
//recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
//buf [0] = 0xff;
unsigned char temp_buf [2];
temp_buf [0]= (unsigned char) 0xff;
temp_buf [1]= '\0';
if (sendto(fd, temp_buf, sizeof (temp_buf), 0, (struct sockaddr *)&remaddr, addrlen) < 0)
perror("sendto");
else
printf("%s \n", "Communication established");
}
【问题讨论】:
-
temp_buf [1]= NULL;-->temp_buf [1]= '\0'; -
@AlterMann 我已经试过了,但是没用
-
如何填充
remaddr和addrlen? -
另外,如何创建套接字?
-
@dbush 我添加了整个代码。感谢您的帮助
标签: c sockets udp buffer sendto