我是 unix 套接字编程的新手。我还没有找到一本舒适的书或教程,所以我真的很挣扎。
这是程序代码:
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include <netinet/in.h>
int main(){
printf("one");
int socketHandle, newSocketHandle, portno;
struct sockaddr_in serverAddress, clientAddress;
printf("two");
portno = 5001;
bzero((char *) &serverAddress, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(portno);
printf("three");
//creating the socket
socketHandle = socket(AF_INET, SOCK_STREAM, 0);
if(socketHandle < 0){
perror("ERROR : Socket not created.");
return -1;
}
printf("Socket created.");
//binding the socket
if(bind(socketHandle, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0){
perror("ERROR : Socket not binded.");
return -1;
}
printf("Socket binded.");
//make the socket listen
listen(socketHandle, 5);
int len = sizeof(clientAddress);
//accept the connection requests
newSocketHandle = accept(socketHandle, (struct sockaddr *) &clientAddress, &len);
if(newSocketHandle < 0){
perror("ERROR : Connection not accepted.");
}
printf("Connection accepted.");
return 0;
}
(我尝试打印one
、、two
和three
进行调试)
但是,即使printf("one")
在第一行也不起作用。光标一直闪烁(表示程序仍在执行中)。我什至不知道上面的程序出了什么问题。使用该bzero()
函数还会引发警告说
warning: incompatible implicit declaration of built-in function ‘bzero’ [enabled by default]
我发现套接字编程很困难,因为不同的网站显示不同的代码。另外,请推荐任何关于 C/C++ 套接字编程的好教程。