TIL (Today I Learned)/Network
[TCP/IP] ํฌํธ(Port)
loki d
2021. 9. 11. 23:51
728x90
ํฌํธ(Port)
์ธํฐ๋ท์ ์ฐ๊ฒฐ๋ ์ปดํจํฐ ๊ฐ์ ์ด๋ฃจ์ด์ง๋ ์๋ฃ์ ๊ตํ์ ํด๋ผ์ด์ธํธ/์๋ฒ ๊ตฌ์กฐ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ํ๋ค.
ํด๋ผ์ด์ธํธ์ ์๋น์ค ์์ฒญ๊ณผ ์๋ฒ์ ์๋ ์ฒ๋ฆฌ๋ ๊ฐ๊ฐ์ ์์ผ์ด ์ฐ๊ฒฐ๋ ํฌํธ๋ฅผ ํตํด ์ด๋ฃจ์ด์ง๋ค.
์ปดํจํฐ ์์คํ
์ 0~65535๊น์ง์ ํฌํธ๋ฅผ ๋๊ณ ์๋ค.
- ์น ์๋ฒ, ์ด๋ฉ์ผ, FTP, ํ ๋ท(Telnet) ๋ฑ ์์ฃผ ์ฌ์ฉํ๋ ์๋น์ค์์ ํด๋น ์๋น์ค๋ฅผ ์ด๋ ์์คํ ์์ ์ ๊ณตํ๋ ๊ฐ์ ๋๋ถ๋ถ ๋์ผํ ํฌํธ๋ก ์ด๋ฃจ์ด์ง๋ค.
- ์น ์๋ฒ๋ ์น ๋ธ๋ผ์ฐ์ ๊ฐ 80๋ฒ ํฌํธ์ ์ฐ๊ฒฐํ๋ฉด ์น ์๋ฒ์ ์ฐ๊ฒฐ๋๋ค. 'http://www.naver.com/index.html'์ฒ๋ผ ํน์ ํฌํธ๋ฅผ ๋ช ์ํ์ง ์์๋ 80๋ฒ ํฌํธ์ ์ฐ๊ฒฐ๋๋ ์ด์ ๋ ๊ธฐ๋ณธ(default) ์ค์ ์ด๊ธฐ ๋๋ฌธ
- ๋ง์ผ ํธ์คํธ A์๋ ์น์๋ฒ๊ฐ 80๋ฒ ํฌํธ์ ์ฐ๊ฒฐ๋์ด ์คํ ์ค์ด๊ณ , ํธ์คํธ B์๋ ์น์๋ฒ๊ฐ 90๋ฒ ํฌํธ์ ์ฐ๊ฒฐ๋์ด ์คํ ์ค์ด๋ฉด ์น ๋ธ๋ผ์ฐ์ ์์ ํธ์คํธ A์ ํธ์คํธ B์ ์น ์๋ฒ์ ์ฐ๊ฒฐ ํ ๋๋ง๋ค ํด๋น ์น ์๋ฒ์ ํฌํธ๋ฅผ ๋ค์ ๋ช ํํ๊ฒ ํด์ผ ํ๋ค.
- http://www.naver.com:8090/index.html'์ฒ๋ผ ํน์ ํฌํธ๋ฅผ ๋ช ์ํ๋ ๊ฒฝ์ฐ๊ฐ ์ข ์ข ์๋ค.
- ์ธํฐ๋ท ํ ๋น ๋ฒํธ ๊ด๋ฆฌ ๊ธฐ๊ด IANA(Internet Assigned Numbers Authority)S๋ ์๋น์ค์ ํฌํธ ๋ฒํธ์ ๋ํ ๊ท์ฝ์ ์ ํ๊ณ ๊ด๋ฆฌํ๋ค.
- IANA 3๊ฐ ์์ญ
- Well-known Port, 0~1023
- Registered Port, 1024~49151
- Dynamic and/or Private Port, 19512~65535
ํฌํธ๋ณ ์๋น์ค ๋ด์ญ์ ์ถ๋ ฅํ๋ ํ๋ก๊ทธ๋จ
/etc/services ํ์ผ์์ ์ ๋ณด๋ฅผ ์ฝ์ด์ค๋ ํ๋ก๊ทธ๋จ์ ๊ตฌํ
ํจ์
#include <netdb.h>
struct servent *getservent(void);
๋ฐํ๊ฐ
- ์ฑ๊ณต ์ : servent ๊ตฌ์กฐ์ฒด์ ๋ํ ํฌ์ธํฐ
- ์คํจ ์ : NULL
๊ตฌ์กฐ์ฒด
struct servent{
char *s_name; // ์๋น์ค ๊ณต์ ๋ช
์นญ
char **s_aliases; // ๋ณ๋ช
๋ช
์นญ
int s_port; // ํฌํธ ๋ฒํธ
char *s_proto; // ์ฌ์ฉํ๋ ํ๋กํ ์ฝ
#include <stdio.h>
#include <netdb.h>
int main() {
struct servent *p;
int n;
while(1){
if (!(p = getservent())) break;
printf("%s\t %d/%s \t", p->s_name, ntohs(p->s_port), p->s_proto);
for(n=0; p->s_aliases[n] != NULL; n++)
printf("%s ", p->s_aliases[n]);
printf("\n");
}
}
IP ์ฃผ์ ๋ณํ
ํจ์
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int inet_aton(const char *cp, struct in_addr *inp);
๋ฐํ ๊ฐ
- ์ฑ๊ณต ์ : 0์ด ์๋ ๊ฐ
- ์คํจ ์ : 0
์ธ์
- cp: 10์ง์์ ์ ์ผ๋ก ๊ตฌ์ฑ๋ ๋ฌธ์์ด ํ์์ IP ์ฃผ์
- inp : ๋คํธ์ํฌ ๋ฐ์ดํธ ์์๋ก ๋ ์ด์ง ๊ฐ์ ์ ์ฅํ๋ 32๋นํธ IP
๊ตฌ์กฐ์ฒด
struct in_addr {
u_longs_addr; //IP ์ฃผ์(๋คํธ์ํฌ ๋ฐ์ดํธ ์์์ ์ด์ง ๊ฐ)
}
ํจ์
#include <arpa/inet.h>
char * inet_ntoa(struct in_addr in);
๋ฐํ ๊ฐ
- ์ฑ๊ณต ์ : 10์ง์์ ์ ์ผ๋ก ๊ตฌ์ฑ๋ ๋ฌธ์์ด ํ์์ IP ์ฃผ์
- ์คํจ ์ : -1
์ธ์
- in : 32 ๋นํธ IP ์ฃผ์๋ฅผ ์ ์ฅํ ๊ตฌ์กฐ์ฒด ๋ณ์
#include <stdio.h>
#include <arpa/inet.h>
int main() {
struct in_addr inp;
const char * ipAddr = "203.249.39.3";
char *addr;
inet_aton(ipAddr, &inp);
printf("ip (dotted decimal_[%s] -> ip(binary)[0x%x]\n", ipAddr, ntohl(inp.s_addr));
addr = inet_ntoa(inp);
printf("ip(binary[0x%x] -> ip(dotted decimal)[%s]\n", ntohl(inp.s_addr), addr);
}