When the c api function in Linux is abnormal, The errno variable (including
Errno. h) assign an integer. Different values indicate different meanings. You can view the cause of the error by checking the value, in actual programming, this solution solves many seemingly inexplicable problems. However, errno is a number, and the specific meaning must be read in errno. H. It is very tedious to check every time. The following methods can be used to conveniently obtain error information:
(1) void perror (const char * s)
Function Description
Perror () is used to output the cause of the previous function error to the standard error (stderr), parameter S
The specified string is printed first, followed by the error cause string. The cause of this error is based on global variables.
The value of errno to determine the string to be output.
(2) char * strerror (INT errno)
Convert the error code to a string error message. You can combine the string and other information and output it to the user interface, for example
Fprintf (stderr, "error in CreateProcess % s, process ID % d
", Strerror (errno), processid)
Note: Assume processid is an acquired integer ID.
(3) printf ("% m", errno );
In addition, not all errors can be obtained through error, for example, the following code segment.
# Include "stdio. H"
# Include "stdlib. H"
# Include "errno. H"
# Include "netdb. H"
# Include "sys/types. H"
# Include "netinet/in. H"
Int main (INT argc, char * argv [])
{
Struct hostent * h;
If (argc! = 2)
{
Fprintf (stderr, "Usage: getip address \ n ");
Exit (1 );
}
If (H = gethostbyname (argv [1]) = NULL)
{
Herror ("gethostbyname ");
Exit (1 );
}
Printf ("Host Name: % s \ n", H-> h_name );
Printf ("IP Address: % s \ n", inet_ntoa (* (struct in_addr *) H-> h_addr )));
Return 0;
}
The code above shows that using the gethostbyname () function, you cannot use perror () to output error messages (because the error code is stored in
H_errno, not errno. Therefore, you need to call the herror () function.
You can simply pass it to gethostbyname ()
One machine name ("bbs.tsinghua.edu.cn"), and then from the returned structure struct hostent
The program that outputs the IP address needs to explain: H-> h_addr
It is a char *, but the inet_ntoa () function must pass a struct in_addr
Structure. Therefore, the above forced conversion of H-> h_addr to struct
In_addr *, and then get all the data through it.