Created
July 17, 2022 01:16
-
-
Save adililhan/82ee0c9d4bb4af894d0385cd33fbcc39 to your computer and use it in GitHub Desktop.
TCP Self-Connect Problem Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <netdb.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <sys/socket.h> | |
| #include <netinet/in.h> | |
| #include <arpa/inet.h> | |
| #include <unistd.h> | |
| int main(int argc, char const *argv[]) | |
| { | |
| int port; | |
| if (argc == 1) { | |
| port = 44600; | |
| } else { | |
| port = atoi(argv[1]); | |
| } | |
| int socketfd, connection_status; | |
| struct sockaddr_in destination, source; | |
| socklen_t len = sizeof(source); | |
| bzero(&destination, sizeof(destination)); | |
| socketfd = socket(AF_INET, SOCK_STREAM, 0); | |
| if (socketfd == -1) { | |
| perror("socket create: "); | |
| exit(1); | |
| } | |
| destination.sin_family = AF_INET; | |
| destination.sin_addr.s_addr = inet_addr("127.0.0.1"); | |
| destination.sin_port = htons(port); | |
| for (;;) { | |
| bzero(&source, sizeof(source)); | |
| connection_status = connect(socketfd, (struct sockaddr *)&destination, sizeof(destination)); | |
| if (getsockname(socketfd, (struct sockaddr *)&source, &len) == -1) { | |
| perror("getsockname error: "); | |
| exit(1); | |
| } | |
| printf("Source port: %d\n", ntohs(source.sin_port)); | |
| printf("Destination port: %d\n", port); | |
| if (connection_status != 0) { | |
| printf("The app's source port number is not the same as the port the app is listening on.\n"); | |
| printf("--\n"); | |
| } else { | |
| printf("Connected - The source and destination ports are the same.\n"); | |
| sleep(100); | |
| exit(0); | |
| } | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment