简体   繁体   中英

Porting an application from little-endian to big-endian architecture

I have a TCP server developed on x86 architecture using C under Linux using berkley socker API. The server runs fine without any problems. But now for some reasons I have to run the server on MIPS architecture which has a big-endian architecture.

The server and the clients communicate through a set of predefined protocol. I will give an example of how a server sends a simple message to the clients:

struct echo_req req;

  req.header.version = OFP_VERSION;
  req.header.type = OFPT_ECHO_REQUEST;
  req.header.length = htons (sizeof req);
  req.header.xid = htonl(y);
  req.data = htonl (456);

char data[sizeof (req)];
data[0] = req.header.version;
data[1] = req.header.type;
memcpy (data + 2, &req.header.length, 2);
memcpy (data + 4, &req.header.xid, 4);
memcpy (data + 8, &req.data, 4);

  if ((send (sock_fd, &data, sizeof (data), 0) == -1))
    {
      printf ("Error in sending echo request message\n");
      exit (-1);
    }
printf("Echo Request sent!\n");

As you can see I use htonl and htons for any type longer than a byte to convert it to network byte order. After making up a packet I serialize and pack the data in char array and finally send it over to the netowrk.

Now before I run my server on Big-endian architecture I wanted to clear out a few things. In my perception as I memcpy the data and pack it, if I send it over the network it shouldn't cause any problems on the big-endian architecture as memcpy will perform a byte by byte copy of the data into the array and hence there shouldn't be any problem with the byte ordering when running on Big-endian. Yet I wanted to get the opinion of you people out there which I persume know a lot more than I do as I am still a beginner in network programming :). Please guide me in this whether I am on the right track or not. All help much appreciated.

Thanks

Yes, memcpy just copies bytes in order from a source to a destination.

Without seeing the rest of your code, it's impossible to say that you've used hton(l|s) everywhere you should. It's also possible that you've done something like copying a floating point number byte for byte, which doesn't necessarily work, independent of endianness issues.

I don't see any obvious problems in the code you've posted above though.

Have you made sure you use ntoh/ntos when receiving data as well?

BTW you should simply use the struct for sending data; re-assembling it into the character array does nothing but take CPU time and possibly bear errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM