Frage

Ich bin immer kein Bytes immer geschickt, mit einem errno von 22 (EINVAL, Invalid Argumente) mit diesem Code. Die destination_host wird an anderer Stelle und bekannt gültig zu sein, so dass ich nicht wirklich sehen, was los ist. MAXMSGSIZE ist 1000. Keine Fehler oder Warnungen. Ich bin Kompilieren mit -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);
}
War es hilfreich?

Lösung

Sie geben die falsche Größe für die Adresse. addr ist wirklich ein struct sockaddr_in, kein struct sockaddr.

Ändern Sie den letzten Parameter von sendto zu sizeof(address)

Andere Tipps

inet_ntop ist wahrscheinlich nicht das, was Sie wollen - es wandelt von Netzwerk (d Draht) -Format in Präsentation Format (das heißt "1.2.3.4"). Versuchen Sie:

address.sin_addr.s_addr = *((unsigned long *)destination_host->h_addr);

Sie haben:

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

Da sizeof(addr) == 4 (oder 8), Verwendung sizeof(*addr).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top