0

This is the code I'm trying:

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdint.h>
#include <string.h>

int main(){
    uint8_t dip[4]={127,0,0,1};
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = 5000;
    memcpy(&serv_addr, dip, 4);
    printf("IP: %s\n", inet_ntoa(serv_addr.sin_addr));

    return 0;
}

And this is the final result on my terminal

IP: 0.0.0.0

I don't understand why I obtained that result. Does anyone know what it's happening?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

1 Answers1

1

The problem is in

  memcpy(&serv_addr, dip, 4);

where you forgot to mention the target member (as nested struct in_addr), you used the structure variable address instead. Do it like

 memcpy(&(serv_addr.sin_addr), dip, 4);

and it should work.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261