UDP Socket 소켓 프로그래밍 질문~!! (포트 열기)

Long_run의 이미지

프로그램 예제 실행 중 궁금한 사항입니다..ㅎㅎ

UDP Socket 생성 예제 중..

serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(5000);

이런식으로 설정을 해주는데 질문할 것은 포트 부분입니다.
포트 부분에 위처럼 포트를 직접 입력해주거나
프로그램 실행시 " ./server.exe 5000 " 과 같이 입력하는 예제들이 많은데..

궁금한점이 어떤 포트던지 상관없이 받을 수는 없는건가요?
대부분 구글링으로 찾은 예제들을 보면 모두 저 부분에 값을 입력하거나..
프로그램 실행시 입력받은 문자열을 바탕으로 제작되어 있더라구요..

제가 하고 싶은 프로그램은..
서버로 들어오는 신호는 IP나 Port에 관계없이 항상 열어두고 모두 받고 싶은데요 ㅎㅎ

제가 원하는 것을 구현하기 위해선 어떠한 방법들이 있을까요?

croae의 이미지

일단 소켓통신에 대해 이론을 좀더 공부하시고 소스 코딩에 들어가시는걸 추천 합니다..
적으신 내용과 같이 addr을 INADDR_ANY로 하였을시 말씀대로 어떤 IP라던지 상관없이 받을수 있습니다.

하지만 포트는 다릅니다... IP가 아파트 동 번호라면 포트는 호수 입니다... 우편물 배달할때 특정 위치의 아파트 동만 적는다고
우편물이 다 가지는 않지요? 호수 까지 적어야 정확하게 배달 되듯이 소켓 통신도 마찬가지로 포트가 맞아야합니다..

사용하시는 포트 번호는 아무거나 사용하셔도 됩니다. 단! 시스템 예약 포트 (Well Known port)는 사용 불가입니다.
예를들어 (22, 21,80, 등등..)

또 UDP 및 TCP 사용포트는 구별됩니다.. 같은 포트를 쓰더라도 사용 프로토콜이 다르면 가능합니다.
즉 UDP 5000번 사용시 TCP 5000번 사용 가능.

Long_run의 이미지

" UDP/IP는 클라이언트와 서버로 나뉘고 1 대 다수의 통신 방식은 아닙니다. "
..는 내용과 croae님 말씀처럼 IP/PORT에 대한 내용까지는 숙지하고 있었는데^^;;

질문의 취지는 제가 원하는 방향으로 만들어낼 수 있는 방법이나 혹은 아이디어가 있는지 궁금해서 올리게 되었습니다..ㅎㅎ
(예를 들어 좀 무식한 방법이지만 프로그램상에서 1부터 사용할 최대 Port까지의
모든 Port를 따로따로 Open 한다던가 -_-;; - 물론 말씀해주신대로 예약포트는 제외해야겠죠ㅎㅎ)

음.. 어쨋든 답변주신 내용은 결론적으론 TCP나 UDP로는 제가 원하는 방향으로의 프로그래밍이 불가능하단 이야기가 되겠군요..

int main(){
do(Anything);
your(Everthing);
best(Everytime);
}

addnull의 이미지

원하시는 기능이 packet sniffer 툴의 기능과 유사한 것 같습니다
그쪽으로 자료를 찾아보심이 좋을 것 같습니다 :)

Long_run의 이미지

먼 여행이 될 것 같은 기분은 착각이겠죠 ㅎㅎ
Keyword 제공에 감사합니다~! ㅎㅎ

찾아보고 댜시 돌아오겠습니다 :)

int main(){
do(Anything);
your(Everthing);
best(Everytime);
}

익명 사용자의 이미지

예를들어 임베디드 보드에서 이더넷 패킷 드라이버를 만든다면,
어떤 프로토콜, 어떤 포트, 어떤 주소이던지에 관계없이
처리가 가능하겠습니다.
하지만 그런환경은 아니시겠죠?

태훈의 이미지

#include <pcap.h>
#include <net/ethernet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
 
#define PROMISCUOUS 1
#define NONPROMISCUOUS 0
 
void callback(u_char *useless, const struct pcap_pkthdr *pkthdr,
    const u_char *packet)
{
    struct ether_header *ep;
    struct iphdr *iph;
    struct udphdr *udph;
    unsigned short ether_type;
    int chcnt = 0;
    int len;
    int i;
 
    // Get Ethernet header.
    ep = (struct ether_header *)packet;
    // Get network layer protocol type.
    ether_type = ntohs(ep->ether_type);
 
    if (ether_type == ETHERTYPE_IP) {
        // Move packet pointer for upper protocol header.
        packet += sizeof(struct ether_header);        
        // Get IP header.
        iph = (struct iphdr *)packet;
 
        // Get transport layer protocol type.
        if (iph->protocol == 17) {
            packet += sizeof(struct iphdr);
            udph = (struct udphdr *)packet;
            len = ntohs(udph->len)-sizeof(struct udphdr);
 
            // Print UDP header infomation.
            printf("UDP packet, source port = %d, dest port = %d, len = %d\n",
                    ntohs(udph->source), ntohs(udph->dest), len);
            // Print Data.
            printf("< Data >\n");
            packet += sizeof(struct udphdr);
            for (i=0; i<len; ++i) {
                printf("%.2X ", packet[i]);
                if ((i % 16) == 15) 
                    printf("\n");
            }
            printf("\n");
        }
     }
}
 
int main(int argc, char **argv)
{
  char *dev;
  char *net;
  char *mask;
  char errbuf[PCAP_ERRBUF_SIZE];
  struct bpf_program fp;
  pcap_t *pcd; // packet caputre descriptor.
  bpf_u_int32 netp;
  bpf_u_int32 maskp;
  struct in_addr net_addr, mask_addr;
 
  dev = pcap_lookupdev(errbuf);
  if (dev == NULL)
  {
      printf("%s\n", errbuf);
      exit(1);
  }
  printf("DEV : %s\n", dev);
 
  // Get netmask
  if (pcap_lookupnet(dev, &netp, &maskp, errbuf) == -1) {
    fprintf(stderr, "%s\n", errbuf);
    return 1;
  }
 
  net_addr.s_addr = netp;
  net = inet_ntoa(net_addr);
  printf("NET : %s\n", net);
  mask_addr.s_addr = maskp;
  mask = inet_ntoa(mask_addr);
  printf("MASK : %s\n", mask);
 
  // Get packet capture descriptor.
  pcd = pcap_open_live(dev, BUFSIZ, NONPROMISCUOUS, -1, errbuf);
  if (pcd == NULL) {
    fprintf(stderr, "%s\n", errbuf);
    return 1;
  }
 
  // Set compile option.
  if (pcap_compile(pcd, &fp, "udp", 0, netp) == -1) {
    fprintf(stderr, "compile error\n");
    return 1; }
 
  // Set packet filter role by compile option.
  if (pcap_setfilter(pcd, &fp) == -1) {
    fprintf(stderr, "set filter error\n");
    return 1;
  }
 
  // Capture packet. When packet captured, call callback function.
  pcap_loop(pcd, 0, callback, NULL);
  return 0;
} 

Just do it!

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.