0

Im working od UDP app and I'm not sure if I'm doing this right. I need to get address into addr.sin_addr.s_addr. Until now I just used addr.sin_addr.s_addr = htonl(INADDR_ANY) but I will need to set specific address goten from user. Am I doing it right when I use addr.sin_addr.s_addr = htonl(adresa)?

Full code:

int main(int argv, char **argc) { strcpy(adresa, "someadress"); int optval; struct sockaddr_in addr;//, incoming_addr; /* create socket */ sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock < 0) { err("socket()"); } /* set reusable flag */ optval = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); /* prepare inet address */ memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); if(strcmp(adresa, "-") == 0) { addr.sin_addr.s_addr = htonl(INADDR_ANY); /* listen on all interfaces */ } else { addr.sin_addr.s_addr = htonl(adresa); /* listen on all interfaces */ } if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) { err("bind"); } for(;;) { } return 0; } 

1 Answer 1

1

The simplest way is with the inet_addr function, which can take an IPv4 address and convert it to an address in network byte order as an in_addr_t. This value can then be stored in sin_addr.s_addr:

addr.sin_addr.s_addr = inet_addr(adresa); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.