Khalil Beldi
Khalil Beldi

Reputation: 39

a question about this strncpy function in socket programming

im currently working on portscanner for my network scanner app with socket in c . i found this code , and i want to understand what's the exact role of strncpy here ! and can someone please expalin this code for my cuz im beginner in network programming and thanks ..

Upvotes: 0

Views: 111

Answers (2)

kiran Biradar
kiran Biradar

Reputation: 12742

  1. strncpy((char*)&sa, "", sizeof sa);

    Here author is trying to set 0 to every byte of sa structure.

    As per strncpy

    If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

    If I were you I would do it this way.

    memset(&sa, 0 , sizeof sa);


  1. strncpy((char*)&sa.sin_addr, (char*) host->h_addr, sizeof sa.sin_addr);

    Here Author is trying to copy char *h_addr which holds first host address to s_addr.

    If I were you I would do it this way.

    sa.sin_addr.s_addr = inet_addr(host->h_addr);

Upvotes: 2

fennecdjay
fennecdjay

Reputation: 56

Well, it looks like it sets sa bits to zero. It's probably equivalent to

memset(&sa, 0, sizeof sa);

or, if your compiler allows it, you can use

struct sockaddr_in sa = {.sin_family = AF_INET };

and get rid of

sa.sin_family = AF_INET;

Upvotes: 0

Related Questions