PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How to send integer array over udp socket in C?

 October 17, 2022     arrays, c, int, sockets     No comments   

Issue

I have to send an int array over an udp socket. Do I have to convert it as char array or as a sequence of byte? What is the standard solution?


Solution

You could just do as follow:

int array[100];
sendto(sockfd, array, sizeof(array), 0, &addr, addrlen);

To recv your array the other side (assuming you always send array of the same size):

int array[100];
recvfrom(sockfd, array, sizeof(array), 0, &addr, &addrlen);

As said in the comments, you have to be carefull about the architecture of the system which send / receive the packet. If you're developping an application for 'standard' computers, you should not have any problem, if you want to be sure:

  • Use a fixed-size type (include stdint.h and use int32_t or whatever is necessary for you.
  • Check for endianess in your code.

Endianess conversion:

// SENDER   

int32_t array[100] = ...;
int32_t arrayToSend[100];
for (int i = 0; i < 100; ++i) {
    arrayToSend[i] = htonl(array[i]);
}
sendto(sockfd, arrayToSend, sizeof(arrayToSend), 0, &addr, addrlen);

// RECEIVER

int32_t array[100];
int32_t arrayReceived[100];
recvfrom(sockfd, arrayReceived, sizeof(arrayReceived), 0, &addr, &addrlen);
for (int i = 0; i < 100; ++i) {
    array[i] = ntohl(arrayReceived[i]);
}


Answered By - Holt
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing