Reputation: 27748
Learning socket programming, and the following is the cut/paste of error parts.
FYI, I was following this tutorial.
Undrestood gethostbyname()
returns struct hostent
struct hostent *gethostbyname(const char *name);
with the following code.
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <netinet/in.h>
5 #include <stdlib.h>
6 #include <strings.h>
7
8 int main(int argc, char *argv[])
9 {
10 int sockfd, portno, n;
11 struct sockaddr_in serv_addr;
12 struct hostent *server;
13
14 server = gethostbyname(argv[1]);
15
16 /* compose serv_addr */
17 bzero( (char *)&serv_addr, sizeof(serv_addr) );
18 serv_addr.sin_family = AF_INET;
19 bcopy( (char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
20 serv_addr.sin_port = htons(portno);
21
22 return 0;
23 }
I have the following gcc error/warning
$gcc client2.c
client2.c: In function ‘main’:
client2.c:14: warning: assignment makes pointer from integer without a cast
client2.c:19: error: dereferencing pointer to incomplete type
client2.c:19: error: dereferencing pointer to incomplete type
Please point me what I m doing wrong?
Upvotes: 2
Views: 1207
Reputation: 19347
Try adding this to the top:
#include <netdb.h>
It's a required include for gethostbyname
. If you type man gethostbyname
at the command line, you'll get the man page, which opens:
The manpages detail which headers you need to include (under SYNOPSIS).
(Hit q to exit man
.)
Upvotes: 9
Reputation: 104080
Note in the bzero(3)
manpage:
4.3BSD. This function is deprecated (marked as LEGACY in
POSIX.1-2001): use memset(3) in new programs. POSIX.1-2008
removes the specification of bzero().
You should definitely use memset(3)
instead of bzero(3)
-- the API is only slightly more verbose but that's not entirely horrible. Same story for bcopy(3)
and memcpy(3)
.
memset(3)
and memcpy(3)
are in <string.h>
, not <strings.h>
, so change that too.
You're using too many casts in your code; when the prototype for a function includes void *
, it'll accept any pointer type as a parameter and the compiler will correctly track the types. Adding a cast will tell the compiler that you know better -- and will, quite often, mask actual errors and warnings.
Also note that gethostbyname(3)
requires the <netdb.h>
header, too.
With these changes in place, your code compiles with fewer warnings:
$ CFLAGS="-Wall -Wextra" make client2
cc -Wall -Wextra client2.c -o client2
client2.c: In function ‘main’:
client2.c:11:25: warning: unused variable ‘n’ [-Wunused-variable]
client2.c:11:9: warning: unused variable ‘sockfd’ [-Wunused-variable]
client2.c:9:14: warning: unused parameter ‘argc’ [-Wunused-parameter]
client2.c:21:31: warning: ‘portno’ is used uninitialized in this function [-Wuninitialized]
(None of them should be a surprise; it's code in progress. Good on you for trying to build the code slowly...)
Upvotes: 5