我是 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++ 套接字编程的好教程。
最佳答案
确保在您的调试消息中打印一个换行符以便它们立即显示。
例子 printf("one\n");
如果您真的不想要换行符,您可以使用 fflush(stdout);
刷新输出。
关于C套接字编程——printf不在屏幕上打印任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17599468/