sockaddr_in causing segfault?
Working on creating a server/client system in C right now, and I'm having a little trouble with the client part. From what I've seen, I need to use sockaddr_in so I can connect to the ser开发者_开发知识库ver. However, I've been getting a segfault every time. I believe that sockaddr_in has something to do with it, as commenting it and it's references later in the program fixes the segfault.
code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
int main(int argc, char** argv)
{
int Csock;
int con;
char *data = 0;
char buf[101] = "";
struct sockaddr_in addr;
Csock = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(3435);
con = connect(Csock, (struct sockaddr*) &addr, sizeof(addr));
write(con, "Text", sizeof("Text"));
*data = read(con, buf, 100);
puts(data);
return 0;
}
sadly, I am rather new to C, so that's as much as I can figure... can anyone tell me a way to go about eliminating the segfault?
Thanks!
Quick comment:
data is a pointer to char which does not point to an allocated memory, so:
*data = read(con, buf, 100);
is invalid! You cannot dereference a NULL pointer.
Also, read returns ssize_t
, and not a char, so perhaps:
ssize_t nread = read(con, buf, 100);
and then print out the nread with printf
.
One immediately-apparent thing that's wrong is taking sizeof &addr
when you mean sizeof addr
. Also you never set the address you want to connect to, only the port. On most systems neither of these errors would cause a crash, but they will keep the program from working.
Also it's advisable never to setup sockaddr
structures directly, but instead use getaddrinfo
.
The problem I think, lies with your connect statement. You need
con = connect(Csock, (struct sockaddr*) &addr, sizeof(addr));
sizeof() returns the size of the object. I don't offhand know what the size of the addr structure is, but the statement sizeof(&addr) will return 4 (assuming 32 bit system) and I'm quite sure that the size of the addr structure is > 4 bytes.
The & is the reference operator (or address of) and gives you the address of a particular structure. Address (in 32 bit systems) are 4 bytes. Usually the types of functions (like the connect function) want the actual size of the structure. This is often done for backwards compatibility purposes so that if the size of the structure changes in some future version of the SDK or library, older code doesn't need to change in order to work with the newer libraries.
精彩评论