C套接字编程——printf不在屏幕上打印任何东西

标签 c sockets

我是 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;
}

(我尝试打印onetwothree用于调试)

但是,即使是第一行中的 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/

相关文章:

c - (int (*)[30]) 中的 (*) 是什么意思?

java - 如何使用so-linger保持服务器连接一段时间

c - 套接字超时: It works, 但为什么以及如何,主要是 select() 函数?

没有发送数据时Java ServerSocket异常

c - 在 C 函数声明中, "..."作为最后一个参数有什么作用?

c++ - 使用 EBP 从堆栈中获取参数

c - 在没有赋值的情况下初始化结构?

c++ - 建库失败 : file format not recognized; treating as linker script

linux - 可能有多少个套接字连接?

c# - Web服务: How to debug System.Net.WebException?