5

このコードでは、エラー番号が22(EINVAL、無効な引数)で、常にバイトが送信されていません。は他のdestination_host場所に設定されており、有効であることがわかっているので、実際に何が起こっているのかわかりません。 MAXMSGSIZEは1000です。エラーや警告はありません。私はコンパイルしています-Wall -Werror -pedantic

char *data_rec;
u_int data_len;

int sockfd;
uint16_t *ns;
struct sockaddr_in address;
struct sockaddr *addr;

char *ip;

int i;
int errno;
int bytes_sent;

data_len = MAXMSGSIZE;
data_rec = malloc(sizeof(char)*MAXMSGSIZE);
ns = malloc(MAXMSGSIZE*sizeof(uint16_t));
ip = malloc(MAXMSGSIZE*sizeof(char));

data_rec = "some random test stuff";

sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sockfd<0) {
    printf("socket() failed\n");
}

inet_ntop(AF_INET,destination_host->h_addr,ip,MAXMSGSIZE);
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(theirPort);
address.sin_addr.s_addr = (unsigned long)ip;

addr = (struct sockaddr*)&address;
bind(sockfd,addr,sizeof(address));
/*Convert the message to uint16_t*/
for(i=0; i<MAXMSGSIZE; i++) {
    ns[i] = htons(data_rec[i]);
}


/* send the message */
bytes_sent = sendto(sockfd, ns, data_len, MSG_DONTWAIT, addr, sizeof(addr));
if(bytes_sent == -1) {
    printf("Error sending: %i\n",errno);
}
4

3 に答える 3

11

アドレスに間違ったサイズを指定しています。addrは実際にはstruct sockaddr_in、ではありませんstruct sockaddr

sendtoの最後のパラメーターをに変更しますsizeof(address)

于 2010-10-24T01:33:08.777 に答える
5

inet_ntopおそらくあなたが望むものではありません-それはネットワーク(すなわちワイヤー)フォーマットからプレゼンテーションフォーマット(すなわち「1.2.3.4」)に変換します。試す:

address.sin_addr.s_addr = *((unsigned long *)destination_host->h_addr);
于 2010-10-24T01:35:14.930 に答える
-1

あなたが持っている:

bytes_sent = sendto(sockfd, ns, data_len, MSG_DONTWAIT, addr, sizeof(addr));

sizeof(addr) == 4(または 8) であるため、 を使用しますsizeof(*addr)

于 2016-12-13T05:31:38.150 に答える