#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <errno.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <IP address> <port>\n", argv[0]);
exit(EXIT_FAILURE);
}
const char *ip = argv[1];
int port = atoi(argv[2]);
int sockfd;
struct sockaddr_in addr;
// 创建socket
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 设置目标地址
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (inet_pton(AF_INET, ip, &addr.sin_addr) <= 0) {
perror("inet_pton");
exit(EXIT_FAILURE);
}
// 尝试连接
if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
if (errno == ECONNREFUSED) {
printf("Port %d on %s is closed\n", port, ip);
} else {
perror("connect");
}
close(sockfd);
exit(EXIT_FAILURE);
}
// 连接成功
printf("Port %d on %s is open\n", port, ip);
close(sockfd);
return 0;
}
TCP获取端口状态Demo
最新推荐文章于 2024-10-31 15:54:32 发布