About socket programming Get client address notes

Source: Internet
Author: User

Because I just hit this one recently and I accidentally stepped on a hole in it, so record this pit.

First, after we are all in the accept function to get the address of the client:

CLIENT_SD = Accept (WATCHER->FD, (struct sockaddr*) &client_addr, &client_len);

After the server receives the accept, the struct struct sockaddr * is used to store the client's address information

We can get to the client IP (dotted decimal string) via Inet_ntoa (CLIENT_ADDR.SIN_ADDR);

When I use it, every time I execute to inet_ntoa (segmentation Fault), the whole person is spartan;

Online search of the information found that INET_NTOA is so used ah????? So???

sprintf (node->client_addr,"%s", Inet_ntoa (CLIENT_ADDR.SIN_ADDR));

Finally in the discovery, the pit is here ...

Use Inet_ntoa must add header file # include <arpa/inet.h>

If the program runs here without warning, it will segmentation Fault

All, in peacetime it is best to turn on the compiler warning is better, otherwise these problems are really ....

About socket programming Get client address notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.