刚试着写C的socket 碰到了一个问题,希望有人帮忙看看~
这是一个客户端用socket发个消息的代码 ,在connect的时候会报错 47 ,查了一下是Address family not supported by protocol family,百度了下好像没找出原因。。 我这是在mac的xcode 下 写的,不知道这个有没有差别~
- (void)sendMsg
{
int client_socket;
if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("creat socket faile\n");
//close(client_socket);
return ;
}
printf("scoket %d create success\n", client_socket);
// struct sockaddr_in cAddr ;
// memset(&cAddr, 0, sizeof(cAddr));
// cAddr.sin_family = AF_INET;
// cAddr.sin_port = htons(0);
// cAddr.sin_addr.s_addr = htons(INADDR_ANY);
//
// if ((bind(client_socket, (struct sockaddr*)&cAddr, sizeof(cAddr)) == -1))
// {
// printf("bind socket faile\n");
// close(client_socket);
// }
const char * server_ip = "192.168.0.6";
struct sockaddr_in sAddr;
memset(&sAddr, 0, sizeof(sAddr));
sAddr.sin_family = AF_INET;
sAddr.sin_port = htons(8011);
inet_aton(server_ip, &sAddr.sin_addr);
int result = connect(client_socket, (struct sockaddr *)&sAddr.sin_addr.s_addr, sizeof(sAddr));
printf("connect result = %d\n", result);
if ( result == 0)
{
printf("connect success\n");
char buf[1024] = "iphone send this msg";
send(client_socket, buf, strlen(buf)+1, 0);
close(client_socket);
}
else
{
printf("connect error code is %d\n", errno);
close(client_socket);
}
}