C语言如何将整数转换成IP地址,请写一个完整的C语言程序谢谢

发布网友 发布时间:2022-04-23 08:40

我来回答

1个回答

热心网友 时间:2022-05-07 19:57

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
//#include <unistd.h>
#include <windows.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <sys/socket.h>
//#include <arpa/inet.h>
#include <winsock.h>
#define DEBUG 0
#define MAX_BACKLOG 32
#define MAX_BUF_LEN 12000
#define NAME "name=dcee"
#define CODE "password=201101"
int net_create(char *net_html) ;
void http_process(int connfd);
int main(int argc, char *argv[])
{
int ret;
int listenfd;
int opt = 1;
int connfd;
struct sockaddr_in servaddr;
struct sockaddr_in cliaddr;
socklen_t addrlen;
unsigned short port;
if (argc != 2) {
printf("Usage: %s port\n", argv[1]);
exit(EXIT_FAILURE);
}
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == -1) {
perror("server->socket");
exit(EXIT_FAILURE);
}
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
memset(&servaddr, 0, sizeof(struct sockaddr_in));
port = atoi(argv[1]);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(listenfd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr_in));
if (ret == -1) {
perror("server->bind");
close(listenfd);
exit(EXIT_FAILURE);
}
ret = listen(listenfd, MAX_BACKLOG);
if (ret == -1) {
perror("server->listen");
close(listenfd);
exit(EXIT_FAILURE);
}
while (1) {
addrlen = sizeof(struct sockaddr_in);
memset(&cliaddr, 0, sizeof(struct sockaddr_in));
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &addrlen);
if (connfd == -1) {
perror("server->accept");
continue;
}
#ifdef DEBUG
printf("server->accept: a new client is comming, and the connfd is %d\n", connfd);
#endif
http_process(connfd);
close(connfd);
}
close(listenfd);
exit(EXIT_SUCCESS);
}

这是完整代码,下面的是绑定ip和端口的部分
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
memset(&servaddr, 0, sizeof(struct sockaddr_in));
port = atoi(argv[1]);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
port的值是预定义的8080;
INADDR_ANY意思是本机ip,你也可以用数字,不过要符合标准追问你这是socket的服务器部分,上面的绑定IP是0.0.0.0IP地址,就是全接收,那客户端那边怎么从外部填入客户端地址?

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com