
; winsock1.asm
; Windows socket example.
; Just sends a message to the client showing his IP address.

	format PE console
	entry start

	include 'win32a.inc'

start:
	push starting_msg
	call dword [printf]
	pop eax

	push wsa_data
	push 0x0101
	call dword [WSAStartup]
	test eax, eax
	jnz .startup_error

	mov word [my_addr+sockaddr_in.sin_family], AF_INET
	mov dword [my_addr+sockaddr_in.sin_addr], 0;INADDR_ANY
	mov ax, 25000
	xchg ah, al
	mov word [my_addr+sockaddr_in.sin_port], ax

	push 0
	push SOCK_STREAM
	push AF_INET
	call dword [socket]
	cmp eax, -1 ;INVALID_SOCKET
	je .socket_error
	mov [my_sock], eax

	push sizeof.sockaddr_in
	push my_addr
	push dword [my_sock]
	call dword [bind]
	test eax, eax
	jnz .bind_error

	push 10
	push dword [my_sock]
	call dword [listen]
	test eax, eax
	jnz .listen_error

.forever:
	mov dword [buffer], sizeof.sockaddr_in
	push buffer
	push client_addr
	push dword [my_sock]
	call dword [accept]
	mov [client_sock], eax

	push dword [client_addr+sockaddr_in.sin_addr]
	call dword [inet_ntoa]
	push eax
	push ip_msg
	push buffer
	call dword [sprintf]
	add esp, 12

	push buffer
	call dword [printf]
	pop ecx

	push 0
	push eax
	push buffer
	push dword [client_sock]
	call dword [send]

	push dword [client_sock]
	call dword [closesocket]

	jmp .forever

	push dword [my_sock]
	call dword [closesocket]

	call dword [WSACleanup]

	push 0
	call dword [exit]

.startup_error:
	mov eax, startup_error_msg
	jmp .error_exit
.socket_error:
	mov eax, socket_error_msg
	jmp .error_exit
.bind_error:
	mov eax, bind_error_msg
	jmp .error_exit
.listen_error:
	mov eax, listen_error_msg
	jmp .error_exit


.error_exit:
	push eax
	call dword [printf]
	call dword [exit]



	section '.data' readable writable
my_sock dd 0
wsa_data db sizeof.WSADATA dup 0
my_addr db sizeof.sockaddr_in dup 0

client_sock dd 0
client_addr db sizeof.sockaddr_in dup 0

buffer db 512 dup 0

ip_msg db 13,10,'Hello client!',13,10,'Your IP address is: %s',13,10,0

starting_msg db 'Starting TCP server.',13,10,0
startup_error_msg db 'Unable to initialize Windows Sockets library.',13,10,0
socket_error_msg db 'Unable to get a socket.',13,10,0
bind_error_msg db 'Unable to bind :(',13,10,0
listen_error_msg db 'Unable to listen :(',13,10,0

	section '.idata' data import readable writable
library msvcrt,'msvcrt.dll',\
	ws2_32,'ws2_32.dll'

import	msvcrt,\
	printf,'printf',\
	sprintf,'sprintf',\
	exit,'exit'

import	ws2_32,\
	WSAStartup,'WSAStartup',\
	socket,'socket',\
	bind,'bind',\
	listen,'listen',\
	accept,'accept',\
	send,'send',\
	inet_ntoa,'inet_ntoa',\
	closesocket,'closesocket',\
	WSACleanup,'WSACleanup'
