2

I've been trying to send a custom frame over UDP using the sendto() commands to another PC. Works fine but as soon as there is a 0 byte in the array it will (ofcourse) recognize it as a \0 value and stop at that byte. How do can I bypass this to then send a 0-Byte (0x00) over the network.

char buffer[26] = {0x06, 0x10, 0x02,
0x05, 0x00, 0x1a, 0x08, 0x01, 0xc0,
0xa8, 0x7e, 0x80, 0x0e, 0x58, 0x08,
0x01, 0xc0, 0xa8, 0x7e, 0x80, 0x0e,
0x58, 0x04, 0x04, 0x02, 0x00};

printf("Enter port # to listen to: \n");
int PORT;
scanf("%d", &PORT);
printf("Enter IP Address to send to: \n");
char SERVER[20];
scanf("%s", SERVER);

struct sockaddr_in si_other;
int s, slen=sizeof(si_other);
char buf[26];
char message[26];
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
    die ("socket()");
}

memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);

if (inet_aton(SERVER, &si_other.sin_addr) == 0) {
    fprintf(stderr, "inet_aton() failed\n");
    exit(1);
}

while(1) {
    printf("Enter message: ");
    gets(message);
    memcpy(message, buffer, 26);

    int te = sendto(s, message, strlen(message), 0,     (struct sockaddr *) & si_other, slen);
    //Send message
    if ( te == -1) {
        die("sendto()");
    }

    //Receive reply and print
    memset(buf,'\0', BUFLEN);

    //Receive Data, blocking
    if(recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) & si_other, & slen) == -1) {
        die("receive()");
    }
    puts(buf);
}

close(s);
return 0;

As you see in the above defined array I have a 0x00 byte at place 5. Sendto will only send the first 4 bytes.

1 Answer 1

1

Don't use strlen() if your string contains valid '\0' characters. I suggest you change:

int te = sendto(s, message, strlen(message), 0, (struct sockaddr *) & si_other, slen);

to:

int te = sendto(s, message, sizeof(message), 0, (struct sockaddr *) & si_other, slen);

Also note that you should not be using gets(), as it is unsafe - use fgets() instead. Change:

gets(message);

to:

fgets(message, sizeof(message), stdin);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.